Что такое ipsec в роутере

Introduction

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 into the 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

Internet Key Exchange Protocol (IKE)

The Internet Key Exchange (IKE) is a protocol that provides authenticated keying material for the 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 the IKE daemon about that, and the IKE daemon initiates a connection to a remote host. IKE daemon responds to remote connection. In both cases, peers establish a 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 the 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 the IKE daemon will have lifetime values (either limiting time, after which SA will become invalid, or the amount of data that can be encrypted by this SA, or both). This phase should match the following settings:
    • IPsec protocol
    • mode (tunnel or transport)
    • authentication method
    • PFS (DH) group
    • lifetime

There are two lifetime values — soft and hard. When SA reaches its soft lifetime threshold, the IKE daemon receives a notice and starts another phase 2 exchange to replace this SA with a fresh one. If SA reaches a hard lifetime, it is discarded.

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

PSK authentication was known to be vulnerable against Offline attacks in «aggressive» mode, however recent discoveries indicate that offline attack is possible also in the case of «main» and «ike2» exchange modes. A general recommendation is to avoid using the PSK authentication method.

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.

The generation of keying material is computationally very expensive. Exempli Gratia, the use of the modp8192 group can take several seconds even on a 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 a 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 ECP Diffie-Hellman (also known as «Oakley») Groups are supported:

Diffie-Hellman Group Name Reference
Group 1 768 bits MODP group RFC 2409
Group 2 1024 bits MODP group 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

More on standards can be found here.

Larger DH groups offer better security but require more CPU power. Here are a few commonly used DH groups with varying levels of security and CPU impact:

DH Group 14 (2048-bit) — Provides a reasonable balance between security and CPU usage. It offers 2048-bit key exchange, which is considered secure for most applications today and is widely supported.

DH Group 5 (1536-bit) — Offers a slightly lower level of security compared to DH Group 14 but has a lower CPU impact due to the smaller key size. It is still considered secure for many scenarios.

DH Group 2 (1024-bit) — Should be used with caution because it provides the least security among commonly used groups. It has a lower CPU impact but is susceptible to attacks, especially as computational power increases. It’s generally not recommended for new deployments.

For optimal security, it’s advisable to use DH Group 19. It’s considered fast and secure. However, DH Group 14 might give large load for your router, DH Group 5 can be a reasonable compromise between security and performance. DH Group 2 should generally be avoided unless you have legacy devices that require it.

The correct way of calculating security for your network infrastructure would be to choose how many bits of security you want and you could see how long it would require to decrypt your data, then you have to choose algorithms. Please see information for reference https://www.keylength.com/en/4/

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

Setup Procedure

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

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.

EAP Authentication methods

Outer Auth Inner Auth
EAP-GTC
EAP-MD5
EAP-MSCHAPv2
EAP-PEAPv0

EAP-MSCHAPv2
EAP-GPSK
EAP-GTC
EAP-MD5
EAP-TLS

EAP-SIM
EAP-TLS
EAP-TTLS

PAP
CHAP
MS-CHAP
MS-CHAPv2
EAP-MSCHAPv2
EAP-GTC
EAP-MD5
EAP-TLS

EAP-TLS on Windows is called «Smart Card or other certificates».

Using ed25519 — authentication is not yet supported.

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 on 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:

  • SHA2 (256, 512)
  • SHA1
  • MD5

Transport mode

In transport mode, the AH header is inserted after the 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, the original IP packet is encapsulated within a new IP packet. All of the original IP packets are authenticated.

Encapsulating Security Payload (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.

Transport mode

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

Tunnel mode

In tunnel mode, an 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.

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 Camellia encryption algorithm added since v4.5
  • DES — 56-bit DES-CBC encryption algorithm;
  • 3DES — 168-bit DES encryption algorithm;

Hardware acceleration

Hardware acceleration allows doing a faster encryption process by using a built-in encryption engine inside the CPU.

List of devices with hardware acceleration is available here

CPU DES and 3DES AES-CBC AES-CTR AES-GCM
MD5 SHA1 SHA256 SHA512 MD5 SHA1 SHA256 SHA512 MD5 SHA1 SHA256 SHA512 MD5 SHA1 SHA256 SHA512
88F7040 no yes yes yes no yes yes yes no yes yes yes no yes yes yes
AL21400 yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes
AL32400 yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes
AL52400 yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes
AL73400 yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes
IPQ-4018 / IPQ-4019 no yes yes no no yes* yes* no no yes* yes* no no no no no
IPQ-6010 no no no no no yes yes yes no yes yes yes no yes yes yes
IPQ-8064 no yes yes no no yes* yes* no no yes* yes* no no no no no
MT7621A yes**** yes**** yes**** no yes yes yes no no no no no no no no no
P1023NSN5CFB no no no no yes** yes** yes** yes** no no no no no no no no
P202ASSE2KFB yes yes yes no yes yes yes yes no no no no no no no no
PPC460GT no no no no yes*** yes*** yes*** yes*** yes*** yes*** yes*** yes*** no no no no
TLR4 (TILE) yes yes yes no yes yes yes no yes yes yes no no no no no
x86 (AES-NI) no no no no yes*** yes*** yes*** yes*** yes*** yes*** yes*** yes*** yes*** yes*** yes*** yes***

* supported only 128 bit and 256 bit key sizes

** only manufactured since 2016, serial numbers that begin with number 5 and 7

*** AES-CBC and AES-CTR only encryption is accelerated, hashing done in software

**** DES is not supported, only 3DES and AES-CBC

IPsec throughput results of various encryption and hash algorithm combinations are published on the MikroTik products page.

Policies

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

Properties

Property Description
action (discard | encrypt | none; Default: encrypt) Specifies what to do with the 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 a policy is used to match packets.
dst-address (IP/IPv6 prefix; Default: 0.0.0.0/32) Destination address to be matched in packets. Applicable when tunnel mode (tunnel=yes) or template (template=yes) is used.
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 the packet, and do not acquire SA from IKE daemon;
  • require — drop the packet and acquire SA;
  • unique — drop the 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).
peer (string; Default: ) Name of the peer on which the policy applies.
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.
src-address (ip/ipv6 prefix; Default: 0.0.0.0/32) Source address to be matched in packets. Applicable when tunnel mode (tunnel=yes) or template (template=yes) is used.
src-port (any | integer:0..65535; Default: any) Source port to be matched in packets. If set to any all ports will be matched.
template (yes | no; Default: no) Creates a template and assigns it to a specified policy group.

Following parameters are used by template:

  • group — name of the policy group to which this template is assigned;
  • src-address, dst-address — Requested subnet must match in both directions(for example 0.0.0.0/0 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.

Read-only properties

Property Description
active (yes | no) Whether this policy is currently in use.
default (yes | no) Whether this is a default system entry.
dynamic (yes | no) Whether this is a dynamically added or generated entry.
invalid (yes | no) Whether this policy is invalid — the possible cause is a duplicate policy with the same src-address and dst-address.
ph2-count (integer) A number of active phase 2 sessions associated with the policy.
ph2-state (expired | no-phase2 | established) Indication of the progress of key establishing.
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).

Policy order is important starting from v6.40. Now it works similarly to firewall filters where policies are executed from top to bottom (priority parameter is removed).

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.

Statistics

This menu shows various IPsec statistics and errors.

Read-only properties

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 the number of packets.
in-state-mode-errors (integer) Transformation mode-specific error.
in-state-sequence-errors (integer) A sequence number is out of a window.
in-state-expired (integer) The state is expired.
in-state-mismatches (integer) The state has a mismatched option, for example, the UDP encapsulation type is mismatched.
in-state-invalid (integer) The state is invalid.
in-template-mismatches (integer) No matching template for states, e.g. inbound SAs are correct but the SP rule is wrong. A possible cause is a 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) The state is expired.
out-policy-blocked (integer) Policy discards.
out-policy-dead (integer) The policy is dead.
out-policy-errors (integer) Policy error.

Proposals

Proposal information that will be sent by IKE daemons to establish SAs for certain policies.

Properties

Property Description
auth-algorithms (md5|null|sha1|sha256|sha512; Default: sha1) Allowed algorithms for authorization. SHA (Secure Hash Algorithm) is stronger but slower. MD5 uses a 128-bit key, sha1-160bit key.
comment (string; Default: )
disabled (yes | no; Default: no) Whether an 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-256-cbc,aes-192-cbc,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: )
pfs-group (ecp256 | ecp384 | ecp521 | modp768 | modp1024 | modp1536 | modp2048 | modp3072 | modp4096 | modp6144 | modp8192 | none; Default: modp1024) The diffie-Helman group used for Perfect Forward Secrecy.

Read-only properties

Property Description
default (yes | no) Whether this is a default system entry.

Groups

In this menu, it is possible to create additional policy groups used by policy templates.

Properties

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

Peers

Peer configuration settings are used to establish connections between IKE daemons. This connection then will be used to negotiate keys and algorithms for SAs. 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 a different exchange-mode is used.

Properties

Property Description
address (IP/IPv6 Prefix; Default: 0.0.0.0/0) If the 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 the largest netmask) will be used.
comment (string; Default: ) Short description of the peer.
disabled (yes | no; Default: no) Whether peer is used to matching remote peer’s prefix.
exchange-mode (aggressive | base | main | ike2; Default: main) Different ISAKMP phase 1 exchange modes according to RFC 2408. the main mode relaxes rfc2409 section 5.4, to allow pre-shared-key authentication in the main mode. ike2 mode enables Ikev2 RFC 7296. Parameters that are ignored by IKEv2 proposal-check, compatibility-options, lifebytes, dpd-maximum-failures, nat-traversal.
local-address (IP/IPv6 Address; Default: ) Routers local address on which Phase 1 should be bounded to.
name (string; Default: )
passive (yes | no; Default: no) When a passive mode is enabled will wait for a remote peer to initiate an IKE connection. The enabled passive mode also indicates that the peer is xauth responder, and disabled passive mode — xauth initiator. When a passive mode is a disabled peer will try to establish not only phase1 but also phase2 automatically, if policies are configured or created during the phase1.
port (integer:0..65535; Default: 500) Communication port used (when a router is an initiator) to connect to remote peer in cases if remote peer uses the non-default port.
profile (string; Default: default) Name of the profile template that will be used during IKE negotiation.
send-initial-contact (yes | no; Default: yes) Specifies whether to send «initial contact» IKE packet or wait for remote side, this packet should trigger the 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.

Read-only properties

Property Description
dynamic (yes | no) Whether this is a dynamically added entry by a different service (e.g L2TP).
responder (yes | no) Whether this peer will act as a responder only (listen to incoming requests) and not initiate a connection.

Profiles

Profiles define a set of parameters that will be used for IKE negotiation during Phase 1. These parameters may be common with other peer configurations.

Properties

Property Description
dh-group (modp768 | modp1024  | modp1536 | modp2048 | modp3072 | modp4096 | modp6144 | modp8192 | ecp256 | ecp384 | ecp521; Default: modp1024,modp2048) Diffie-Hellman group (cipher strength)
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.
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.
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.
name (string; Default: )
nat-traversal (yes | no; Default: yes) Use Linux NAT-T mechanism to solve IPsec incompatibility with NAT routers between IPsec peers. This can only be used with ESP protocol (AH is not supported by design, as it signs the complete packet, including the 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.
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 the proposed lifetime is longer than the default then reject the proposal otherwise accept a proposed lifetime

Identities

Identities are configuration parameters that are specific to the remote peer. The main purpose of identity is to handle authentication and verify the peer’s integrity.

Properties

Property Description
auth-method (digital-signature | eap | eap-radius | pre-shared-key | pre-shared-key-xauth | rsa-key | rsa-signature-hybrid; Default: pre-shared-key) Authentication method:

  • digital-signature — authenticate using a pair of RSA certificates;
  • eap — IKEv2 EAP authentication for initiator (peer with a netmask of /32). Must be used together with eap-methods;
  • eap-radius — IKEv2 EAP RADIUS passthrough authentication for the responder (RFC 3579). A server certificate in this case is required. If a server certificate is not specified then only clients supporting EAP-only (RFC 5998) will be able to connect. Note that the EAP method should be compatible with EAP-only;
  • pre-shared-key — authenticate by a password (pre-shared secret) string shared between the peers (not recommended since an offline attack on the pre-shared key is possible);
  • rsa-key — authenticate using an RSA key imported in keys menu. Only supported in IKEv1;
  • pre-shared-key-xauth — authenticate by a password (pre-shared secret) string shared between the peers + XAuth username and password. Only supported in IKEv1;
  • rsa-signature-hybrid — responder certificate authentication with initiator XAuth. Only supported in IKEv1.
certificate (string; Default: ) Name of a certificate listed in System/Certificates (signing packets; the certificate must have the private key). Applicable if digital signature authentication method (auth-method=digital-signature) or EAP (auth-method=eap) is used.
comment (string; Default: ) Short description of the identity.
disabled (yes | no; Default: no) Whether identity is used to match remote peers.
eap-methods (eap-mschapv2 | eap-peap | eap-tls | eap-ttls; Default: eap-tls) All EAP methods requires whole certificate chain including intermediate and root CA certificates to be present in System/Certificates menu. Also, the username and password (if required by the authentication server) must be specified. Multiple EAP methods may be specified and will be used in a specified order. Currently supported EAP methods:

  • eap-mschapv2;
  • eap-peap — also known as PEAPv0/EAP-MSCHAPv2;
  • eap-tls — requires additional client certificate specified under certificate parameter;
  • eap-ttls.
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.
key (string; Default: ) Name of the private key from keys menu. Applicable if RSA key authentication method (auth-method=rsa-key) is used.
match-by (remote-id | certificate; Default: remote-id) Defines the logic used for peer’s identity validation.

  • remote-id — will verify the peer’s ID according to remote-id setting.
  • certificate will verify the peer’s certificate with what is specified under remote-certificate setting.
mode-config (none | *request-only | string; Default: none) Name of the configuration parameters from mode-config menu. When parameter is set mode-config is enabled.
my-id (auto | address | fqdn | user-fqdn | key-id; Default: auto) On initiator, this controls what ID_i is sent to the responder. On responder, this controls what ID_r is sent to the initiator. In IKEv2, responder also expects this ID in received ID_r from initiator.

  • auto — tries to use correct ID automatically: IP for pre-shared key, SAN (DN if not present) for certificate based connections;
  • address — IP address is used as ID;
  • dn — the binary Distinguished Encoding Rules (DER) encoding of an ASN.1 X.500 Distinguished Name;
  • fqdn — fully qualified domain name;
  • key-id — use the specified key ID for the identity;
  • user fqdn — specifies a fully-qualified username string, for example, «user@domain.com».
notrack-chain (string; Default: ) Adds IP/Firewall/Raw rules matching IPsec policy to a specified chain. Use together with generate-policy.
password (string; Default: ) XAuth or EAP password. Applicable if pre-shared key with XAuth authentication method (auth-method=pre-shared-key-xauth) or EAP (auth-method=eap) is used.
peer (string; Default: ) Name of the peer on which the identity applies.
policy-template-group (none | string; Default: default) If generate-policy is enabled, traffic selectors are checked against templates from the same group. If none of the templates match, Phase 2 SA will not be established.
remote-certificate (string; Default: ) Name of a certificate (listed in System/Certificates) for authenticating the remote side (validating packets; no private key required). If a remote-certificate is not specified then the received certificate from a remote peer is used and checked against CA in the certificate menu. Proper CA must be imported in a certificate store. If remote-certificate and match-by=certificate is specified, only the specific client certificate will be matched. Applicable if digital signature authentication method (auth-method=digital-signature) is used.
remote-id (auto | fqdn | user-fqdn | key-id | ignore; Default: auto) This parameter controls what ID value to expect from the remote peer. Note that all types except for ignoring will verify remote peer’s ID with a received certificate. In case when the peer sends the certificate name as its ID, it is checked against the certificate, else the ID is checked against Subject Alt. Name.

  • auto — accept all ID’s;
  • address — IP address is used as ID;
  • dn — the binary Distinguished Encoding Rules (DER) encoding of an ASN.1 X.500 Distinguished Name;
  • fqdn — fully qualified domain name. Only supported in IKEv2;
  • user fqdn — a fully-qualified username string, for example, «user@domain.com». Only supported in IKEv2;
  • key-id — specific key ID for the identity. Only supported in IKEv2;
  • ignore — do not verify received ID with certificate (dangerous).
remote-key (string; Default: ) Name of the public key from keys menu. Applicable if RSA key authentication method (auth-method=rsa-key) is used.
secret (string; Default: ) Secret string. If it starts with ‘0x’, it is parsed as a hexadecimal value. Applicable if pre-shared key authentication method (auth-method=pre-shared-key and auth-method=pre-shared-key-xauth) is used.
username (string; Default: ) XAuth or EAP username. Applicable if pre-shared key with XAuth authentication method (auth-method=pre-shared-key-xauth) or EAP (auth-method=eap) is used.

Read only properties

Property Description
dynamic (yes | no) Whether this is a dynamically added entry by a different service (e.g L2TP).

Active Peers

This menu provides various statistics about remote peers that currently have established phase 1 connection.

Read only properties

Property Description
dynamic-address (ip/ipv6 address) Dynamically assigned an IP address by mode config
last-seen (time) Duration since the last message received by this peer.
local-address (ip/ipv6 address) Local address on the router used by this peer.
natt-peer (yes | no) Whether NAT-T is used for this peer.
ph2-total (integer) The total amount of active IPsec security associations.
remote-address (ip/ipv6 address) The remote peer’s ip/ipv6 address.
responder (yes | no) Whether the connection is initiated by a remote peer.
rx-bytes (integer) The total amount of bytes received from this peer.
rx-packets (integer) The total amount of packets received from this peer.
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».
tx-bytes (integer) The total amount of bytes transmitted to this peer.
tx-packets (integer) The total amount of packets transmitted to this peer.
uptime (time) How long peers are in an established state.

Commands

Property Description
kill-connections () Manually disconnects all remote peers.

Mode configs

ISAKMP and IKEv2 configuration attributes are configured in this menu.

Properties

Property Description
address (none | string; Default: ) Single IP address for the initiator instead of specifying a whole address pool.
address-pool (none | string; Default: ) Name of the address pool from which the responder will try to assign address if mode-config is enabled.
address-prefix-length (integer [1..32]; Default: ) Prefix length (netmask) of the assigned address from the pool.
comment (string; Default: )
name (string; Default: )
responder (yes | no; Default: no) Specifies whether the configuration will work as an initiator (client) or responder (server). The initiator will request for mode-config parameters from the responder.
split-dns List of DNS names that will be resolved using a system-dns=yes or static-dns= setting.
split-include (list of IP prefix; Default: ) List of subnets in CIDR format, which to tunnel. Subnets will be sent to the peer using the CISCO UNITY extension, a remote peer will create specific dynamic policies.
src-address-list (address list; Default: ) Specifying an address list will generate dynamic source NAT rules. This parameter is only available with responder=no. A roadWarrior client with NAT
static-dns (list of 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.

Read-only properties

Property Description
default (yes | no) Whether this is a default system entry.

Not all IKE implementations support multiple split networks provided by the split-include option.

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

Both attributes Cisco Unity Split DNS (attribute type 28675) and RFC8598 (attribute type 25) are supported, ROS will answer to these attributes but only as responder. 

It is not possible to use system-dns and static-dns at the same time, ROS can use only one DNS.

Installed SAs

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

Read-only properties

Property Description
AH (yes | no) Whether AH protocol is used by this SA.
ESP (yes | no) Whether ESP protocol is used by this SA.
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 (md5 | null | sha1 | …) Currently used authentication algorithm.
auth-key (string) Used authentication key.
current-bytes (64-bit integer) A number of bytes seen by this SA.
dst-address (IP) The destination address of this SA.
enc-algorithm (des | 3des | aes-cbc | …) Currently used encryption algorithm.
enc-key (string) Used encryption key.
enc-key-size (number) Used encryption key length.
expires-in (yes | no) Time left until rekeying.
hw-aead (yes | no) Whether this SA is hardware accelerated.
replay (integer) Size of replay window in bytes.
spi (string) Security Parameter Index identification tag
src-address (IP) The source address of this SA.
state (string) Shows the current state of the SA («mature», «dying» etc)

Commands

Property Description
flush () Manually removes all installed security associations.

Keys

This menu lists all imported public and private keys, that can be used for peer authentication. Menu has several commands to work with keys.

Properties

Property Description
name (string; Default: )

Read-only properties

Property Description
key-size (1024 | 2048 | 4096) Size of this key.
private-key (yes | no) Whether this is a private key.
rsa (yes | no) Whether this is an RSA key.

Commands

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 a private key. Takes two parameters, name of the newly generated key and key size 1024,2048 and 4096.
import (file-name; name) Import key from file.

Settings

Property Description
accounting (yes | no; Default: ) Whether to send RADIUS accounting requests to a RADIUS server. Applicable if EAP Radius (auth-method=eap-radius) or pre-shared key with XAuth authentication method (auth-method=pre-shared-key-xauth) is used.
interim-update (time; Default: ) The interval between each consecutive RADIUS accounting Interim update. Accounting must be enabled.
xauth-use-radius (yes | no; Default: ) Whether to use Radius client for XAuth users or not.  Property is only applicable to peers using the IKEv1 exchange mode.

Application Guides

RoadWarrior client with NAT

Consider setup as illustrated below. RouterOS acts as a RoadWarrior client connected to Office allowing access to its internal resources.

A tunnel is established, a local mode-config IP address is received and a set of dynamic policies are generated.

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

1 DA src-address=192.168.77.254/32 src-port=any dst-address=10.5.8.0/24 dst-port=any protocol=all 
action=encrypt level=unique ipsec-protocols=esp tunnel=yes sa-src-address=10.155.107.8 
sa-dst-address=10.155.107.9 proposal=default ph2-count=1 

2 DA src-address=192.168.77.254/32 src-port=any dst-address=192.168.55.0/24 dst-port=any protocol=all 
action=encrypt level=unique ipsec-protocols=esp tunnel=yes sa-src-address=10.155.107.8 
sa-dst-address=10.155.107.9 proposal=default ph2-count=1 

Currently, only packets with a source address of 192.168.77.254/32 will match the IPsec policies. For a local network to be able to reach remote subnets, it is necessary to change the source address of local hosts to the dynamically assigned mode config IP address. It is possible to generate source NAT rules dynamically. This can be done by creating a new address list that contains all local networks that the NAT rule should be applied. In our case, it is 192.168.88.0/24.

/ip firewall address-list add address=192.168.88.0/24 list=local-RW

By specifying the address list under the mode-config initiator configuration, a set of source NAT rules will be dynamically generated.

/ip ipsec mode-config set [ find name="request-only" ] src-address-list=local-RW

When the IPsec tunnel is established, we can see the dynamically created source NAT rules for each network. Now every host in 192.168.88.0/24 is able to access Office’s internal resources.

[admin@mikrotik] > ip firewall nat print 
Flags: X - disabled, I - invalid, D - dynamic 
0 D ;;; ipsec mode-config
chain=srcnat action=src-nat to-addresses=192.168.77.254 dst-address=192.168.55.0/24 src-address-list=local-RW

1 D ;;; ipsec mode-config
chain=srcnat action=src-nat to-addresses=192.168.77.254 dst-address=10.5.8.0/24 src-address-list=local-RW

Allow only IPsec encapsulated 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 nonencrypted L2TP connection attempts.

There are several ways how to achieve this:

  • Using IPsec policy matcher in firewall;
  • Using generic IPsec policy with action set to 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

Let’s set up an IPsec policy matcher to accept all packets that matched any of the IPsec policies and drop the rest:

add chain=input comment="ipsec policy matcher" in-interface=WAN ipsec-policy=in,ipsec
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 a specific source address and drop the rest we could set up the following rules:

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

For L2TP rule set would be:

add chain=input comment="ipsec policy matcher" in-interface=WAN ipsec-policy=in,ipsec protocol=udp dst-port=1701
add action=drop chain=input protocol=udp dst-port=1701 comment="drop l2tp" in-interface=WAN log=yes

Using generic IPsec policy

The trick of this method is to add a default policy with an action drop. Let’s assume we are running an L2TP/IPsec server on a public 1.1.1.1 address and we want to drop all nonencrypted L2TP:

/ip ipsec policy
add src-address=1.1.1.1 dst-address=0.0.0.0/0 sa-src-address=1.1.1.1 protocol=udp src-port=1701 tunnel=yes action=discard

Now router will drop any L2TP unencrypted incoming traffic, but after a 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.

Policy order is important! For this to work, make sure the static drop policy is below the dynamic policies. Move it below the policy template if necessary.

[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 D src-address=1.1.1.1/32 src-port=1701 dst-address=10.5.130.71/32
dst-port=any protocol=udp action=encrypt level=require
ipsec-protocols=esp tunnel=no sa-src-address=1.1.1.1
sa-dst-address=10.5.130.71

2 src-address=1.1.1.1/32 src-port=1701 dst-address=0.0.0.0/0
dst-port=any protocol=udp action=discard level=unique
ipsec-protocols=esp tunnel=yes sa-src-address=1.1.1.1
sa-dst-address=0.0.0.0 proposal=default manual-sa=none

Manually specifying local-address parameter under Peer configuration

Using different routing table

IPsec, as any other service in RouterOS, uses the main routing table regardless of what local-address parameter is used for Peer configuration. It is necessary to apply routing marks to both IKE and IPSec traffic.

Consider the following example. There are two default routes — one in the main routing table and another in the routing table «backup». It is necessary to use the backup link for the IPsec site to site tunnel.

[admin@pair_r1] > /ip route print detail 
Flags: X - disabled, A - active, D - dynamic, C - connect, S - static, r - rip, b - bgp, o - ospf, m - mme, B - blackhole, U - unreachable, P - prohibit 
0 A S dst-address=0.0.0.0/0 gateway=10.155.107.1 gateway-status=10.155.107.1 reachable via ether1 distance=1 scope=30 target-scope=10 routing-mark=backup 

1 A S dst-address=0.0.0.0/0 gateway=172.22.2.115 gateway-status=172.22.2.115 reachable via ether2 distance=1 scope=30 target-scope=10 

2 ADC dst-address=10.155.107.0/25 pref-src=10.155.107.8 gateway=ether1 gateway-status=ether1 reachable distance=0 scope=10 

3 ADC dst-address=172.22.2.0/24 pref-src=172.22.2.114 gateway=ether2 gateway-status=ether2 reachable distance=0 scope=10 

4 ADC dst-address=192.168.1.0/24 pref-src=192.168.1.1 gateway=bridge-local gateway-status=ether2 reachable distance=0 scope=10 

[admin@pair_r1] > /ip firewall nat print 
Flags: X - disabled, I - invalid, D - dynamic 
0 chain=srcnat action=masquerade out-interface=ether1 log=no log-prefix="" 

1 chain=srcnat action=masquerade out-interface=ether2 log=no log-prefix="" 

IPsec peer and policy configurations are created using the backup link’s source address, as well as the NAT bypass rule for IPsec tunnel traffic.

/ip ipsec peer
add address=10.155.130.136/32 local-address=10.155.107.8 secret=test
/ip ipsec policy
add sa-src-address=10.155.107.8 src-address=192.168.1.0/24 dst-address=172.16.0.0/24 sa-dst-address=10.155.130.136 tunnel=yes
/ip firewall nat
add action=accept chain=srcnat src-address=192.168.1.0/24 dst-address=172.16.0.0/24 place-before=0

Currently, we see «phase1 negotiation failed due to time up» errors in the log. It is because IPsec tries to reach the remote peer using the main routing table with an incorrect source address. It is necessary to mark UDP/500, UDP/4500, and ipsec-esp packets using Mangle:

/ip firewall mangle
add action=mark-connection chain=output connection-mark=no-mark dst-address=10.155.130.136 dst-port=500,4500 new-connection-mark=ipsec passthrough=yes protocol=udp
add action=mark-connection chain=output connection-mark=no-mark dst-address=10.155.130.136 new-connection-mark=ipsec passthrough=yes protocol=ipsec-esp
add action=mark-routing chain=output connection-mark=ipsec new-routing-mark=backup passthrough=no

Using the same routing table with multiple IP addresses

Consider the following example. There are multiple IP addresses from the same subnet on the public interface. Masquerade rule is configured on out-interface. It is necessary to use one of the IP addresses explicitly.

[admin@pair_r1] > /ip address print 
Flags: X - disabled, I - invalid, D - dynamic 
# ADDRESS NETWORK INTERFACE
0 192.168.1.1/24 192.168.1.0 bridge-local
1 172.22.2.1/24 172.22.2.0 ether1
2 172.22.2.2/24 172.22.2.0 ether1
3 172.22.2.3/24 172.22.2.0 ether1

[admin@pair_r1] > /ip route print 
Flags: X - disabled, A - active, D - dynamic, C - connect, S - static, r - rip, b - bgp, o - ospf, m - mme, B - blackhole, U - unreachable, P - prohibit 
# DST-ADDRESS PREF-SRC GATEWAY DISTANCE
1 A S 0.0.0.0/0 172.22.2.115 1
3 ADC 172.22.2.0/24 172.22.2.1 ether1 0
4 ADC 192.168.1.0/24 192.168.1.1 bridge-local 0

[admin@pair_r1] /ip firewall nat> print 
Flags: X - disabled, I - invalid, D - dynamic 
0 chain=srcnat action=masquerade out-interface=ether1 log=no log-prefix="" 

IPsec peer and policy configuration is created using one of the public IP addresses.

/ip ipsec peer
add address=10.155.130.136/32 local-address=172.22.2.3 secret=test
/ip ipsec policy
add sa-src-address=172.22.2.3 src-address=192.168.1.0/24 dst-address=172.16.0.0/24 sa-dst-address=10.155.130.136 tunnel=yes
/ip firewall nat
add action=accept chain=srcnat src-address=192.168.1.0/24 dst-address=172.16.0.0/24 place-before=0

Currently, the phase 1 connection uses a different source address than we specified, and «phase1 negotiation failed due to time up» errors are shown in the logs. This is because masquerade is changing the source address of the connection to match the pref-src address of the connected route. The solution is to exclude connections from the public IP address from being masqueraded.

/ip firewall nat
add action=accept chain=srcnat protocol=udp src-port=500,4500 place-before=0

Application examples

Site to Site IPsec (IKEv1) tunnel

Consider setup as illustrated below. Two remote office routers are connected to the internet and office workstations are behind NAT. Each office has its own local subnet, 10.1.202.0/24 for Office1 and 10.1.101.0/24 for Office2. Both remote offices need secure tunnels to local networks behind routers.

Site 1 configuration

Start off by creating a new Phase 1profileand Phase 2proposalentries using stronger or weaker encryption parameters that suit your needs. It is advised to create separate entries for each menu so that they are unique for each peer in case it is necessary to adjust any of the settings in the future. These parameters must match between the sites or else the connection will not establish.

/ip ipsec profile
add dh-group=modp2048 enc-algorithm=aes-128 name=ike1-site2
/ip ipsec proposal
add enc-algorithms=aes-128-cbc name=ike1-site2 pfs-group=modp2048

Continue by configuring a peer. Specify the address of the remote router. This address should be reachable through UDP/500 and UDP/4500 ports, so make sure appropriate actions are taken regarding the router’s firewall. Specify the name for this peer as well as the newly created profile.

/ip ipsec peer
add address=192.168.80.1/32 name=ike1-site2 profile=ike1-site2

The next step is to create an identity. For a basic pre-shared key secured tunnel, there is nothing much to set except for a strong secret and the peer to which this identity applies.

/ip ipsec identity
add peer=ike1-site2 secret=thisisnotasecurepsk

If security matters, consider using IKEv2 and a different auth-method.

Lastly, create a policy that controls the networks/hosts between whom traffic should be encrypted.

/ip ipsec policy
add src-address=10.1.202.0/24 src-port=any dst-address=10.1.101.0/24 dst-port=any tunnel=yes action=encrypt proposal=ike1-site2 peer=ike1-site2

Site 2 configuration

Office 2 configuration is almost identical to Office 1 with proper IP address configuration. Start off by creating a new Phase 1 profile and Phase 2 proposal entries:

/ip ipsec profile
add dh-group=modp2048 enc-algorithm=aes-128 name=ike1-site1
/ip ipsec proposal
add enc-algorithms=aes-128-cbc name=ike1-site1 pfs-group=modp2048

Next is the peer and identity:

/ip ipsec peer
add address=192.168.90.1/32 name=ike1-site1 profile=ike1-site1
/ip ipsec identity
add peer=ike1-site1 secret=thisisnotasecurepsk

When it is done, create a policy:

/ip ipsec policy
add src-address=10.1.101.0/24 src-port=any dst-address=10.1.202.0/24 dst-port=any tunnel=yes action=encrypt proposal=ike1-site1 peer=ike1-site1

At this point, the tunnel should be established and two IPsec Security Associations should be created on both routers:

/ip ipsec
active-peers print
installed-sa print

NAT and Fasttrack Bypass

At this point if you try to send traffic over the IPsec tunnel, it will not work, packets will be lost. This is because both routers have NAT rules (masquerade) that are changing source addresses before a packet is encrypted. A router is unable to encrypt the packet because the source address does not match the address specified in the policy configuration. For more information see the IPsec packet flow example.

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

Office 1 router:

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

Office 2 router:

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

If you previously tried to establish an IP connection before the NAT bypass rule was added, you have to clear the connection table from the existing connection or restart both routers.

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

Another issue is if you have IP/Fasttrack enabled, the 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=10.1.101.0/24 dst-address=10.1.202.0/24 connection-state=established,related
add chain=forward action=accept place-before=1
src-address=10.1.202.0/24 dst-address=10.1.101.0/24 connection-state=established,related

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

The solution is to use IP/Firewall/Raw to bypass connection tracking, that way eliminating the need for filter rules listed above and reducing the load on CPU by approximately 30%.

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

Site to Site GRE tunnel over IPsec (IKEv2) using DNS

This example explains how it is possible to establish a secure and encrypted GRE tunnel between two RouterOS devices when one or both sites do not have a static IP address. Before making this configuration possible, it is necessary to have a DNS name assigned to one of the devices which will act as a responder (server). For simplicity, we will use RouterOS built-in DDNS service IP/Cloud.

Site 1 (server) configuration

This is the side that will listen to incoming connections and act as a responder. We will use mode config to provide an IP address for the second site, but first, create a loopback (blank) bridge and assign an IP address to it that will be used later for GRE tunnel establishment.

/interface bridge 
add name=loopback
/ip address
add address=192.168.99.1 interface=loopback

Continuing with the IPsec configuration, start off by creating a new Phase 1 profile and Phase 2 proposal entries using stronger or weaker encryption parameters that suit your needs. Note that this configuration example will listen to all incoming IKEv2 requests, meaning the profile configuration will be shared between all other configurations (e.g. RoadWarrior).

/ip ipsec profile
add dh-group=ecp256,modp2048,modp1024 enc-algorithm=aes-256,aes-192,aes-128 name=ike2
/ip ipsec proposal
add auth-algorithms=null enc-algorithms=aes-128-gcm name=ike2-gre pfs-group=none

Next, create a new mode config entry with responder=yes. This will provide an IP configuration for the other site as well as the host (loopback address) for policy generation.

/ip ipsec mode-config
add address=192.168.99.2 address-prefix-length=32 name=ike2-gre split-include=192.168.99.1/32 system-dns=no

It is advised to create a new policy group to separate this configuration from any existing or future IPsec configuration.

/ip ipsec policy group
add name=ike2-gre

Now it is time to set up a new policy template that will match the remote peers new dynamic address and the loopback address.

/ip ipsec policy
add dst-address=192.168.99.2/32 group=ike2-gre proposal=ike2-gre src-address=192.168.99.1/32 template=yes

The next step is to createpeer configuration that will listen to all IKEv2 requests. If you already have such an entry, you can skip this step.

/ip ipsec peer
add exchange-mode=ike2 name=ike2 passive=yes profile=ike2

Lastly, set up an identity that will match our remote peer by pre-shared-key authentication with a specific secret.

/ip ipsec identity
add generate-policy=port-strict mode-config=ike2-gre peer=ike2 policy-template-group=ike2-gre secret=test

The server side is now configured and listening to all IKEv2 requests. Please make sure the firewall is not blocking UDP/4500 port.

The last step is to create the GRE interface itself. This can also be done later when an IPsec connection is established from the client-side.

/interface gre
add local-address=192.168.99.1 name=gre-tunnel1 remote-address=192.168.99.2

Configure IP address and route to remote network through GRE interface.

/ip address
add address=172.16.1.1/30 interface=gre-tunnel1
/ip route
add dst-network=10.1.202.0/24 gateway=172.16.1.2

Site 2 (client) configuration

Similarly to server configuration, start off by creating a new Phase 1 profile and Phase 2 proposal configurations. Since this site will be the initiator, we can use a more specific profile configuration to control which exact encryption parameters are used, just make sure they overlap with what is configured on the server-side.

/ip ipsec profile
add dh-group=ecp256 enc-algorithm=aes-256 name=ike2-gre
/ip ipsec proposal
add auth-algorithms=null enc-algorithms=aes-128-gcm name=ike2-gre pfs-group=none

Next, create a new mode config entry with responder=no. This will make sure the peer requests IP and split-network configuration from the server.

/ip ipsec mode-config
add name=ike2-gre responder=no

It is also advised to create a new policy group to separate this configuration from any existing or future IPsec configuration.

/ip ipsec policy group
add name=ike2-gre

Create a new policy template on the client-side as well.

/ip ipsec policy
add dst-address=192.168.99.1/32 group=ike2-gre proposal=ike2-gre src-address=192.168.99.2/32 template=yes

Move on to peer configuration. Now we can specify the DNS name for the server under the address parameter. Obviously, you can use an IP address as well.

/ip ipsec peer
add address=n.mynetname.net exchange-mode=ike2 name=p1.ez profile=ike2-gre

Lastly, create an identity for our newly created peers.

/ip ipsec identity
add generate-policy=port-strict mode-config=ike2-gre peer=p1.ez policy-template-group=ike2-gre secret=test

If everything was done properly, there should be a new dynamic policy present.

/ip ipsec policy print 
Flags: T - template, X - disabled, D - dynamic, I - invalid, A - active, * - default 
0 T * group=default src-address=::/0 dst-address=::/0 protocol=all proposal=default template=yes

1 T group=ike2-gre src-address=192.168.99.2/32 dst-address=192.168.99.1/32 protocol=all proposal=ike2-gre template=yes

2 DA src-address=192.168.99.2/32 src-port=any dst-address=192.168.99.1/32 dst-port=any protocol=all action=encrypt level=unique ipsec-protocols=esp 
tunnel=yes sa-src-address=192.168.90.1 sa-dst-address=(current IP of n.mynetname.net) proposal=ike2-gre ph2-count=1 

A secure tunnel is now established between both sites which will encrypt all traffic between 192.168.99.2 <=> 192.168.99.1 addresses. We can use these addresses to create a GRE tunnel.

/interface gre
add local-address=192.168.99.2 name=gre-tunnel1 remote-address=192.168.99.1

Configure IP address and route to remote network through GRE interface.

/ip address
add address=172.16.1.2/30 interface=gre-tunnel1
/ip route
add dst-network=10.1.101.0/24 gateway=172.16.1.1

Road Warrior setup using IKEv2 with RSA authentication

This example explains how to establish a secure IPsec connection between a device connected to the Internet (road warrior client) and a device running RouterOS acting as a server.

RouterOS server configuration

Before configuring IPsec, it is required to set up certificates. It is possible to use a separate Certificate Authority for certificate management, however in this example, self-signed certificates are generated in RouterOS System/Certificates menu. Some certificate requirements should be met to connect various devices to the server:

  • Common name should contain IP or DNS name of the server;
  • SAN (subject alternative name) should have IP or DNS of the server;
  • EKU (extended key usage) tls-server and tls-client are required.

Considering all requirements above, generate CA and server certificates:

/certificate
add common-name=ca name=ca
sign ca ca-crl-host=2.2.2.2
add common-name=2.2.2.2 subject-alt-name=IP:2.2.2.2 key-usage=tls-server name=server1
sign server1 ca=ca

Now that valid certificates are created on the router, add a new Phase 1 profile and Phase 2 proposal entries with pfs-group=none:

/ip ipsec profile
add name=ike2
/ip ipsec proposal
add name=ike2 pfs-group=none

Mode config is used for address distribution from IP/Pools:

/ip pool
add name=ike2-pool ranges=192.168.77.2-192.168.77.254
/ip ipsec mode-config
add address-pool=ike2-pool address-prefix-length=32 name=ike2-conf

Since that the policy template must be adjusted to allow only specific network policies, it is advised to create a separate policy group and template.

/ip ipsec policy group
add name=ike2-policies
/ip ipsec policy
add dst-address=192.168.77.0/24 group=ike2-policies proposal=ike2 src-address=0.0.0.0/0 template=yes

Create a new IPsec peer entry that will listen to all incoming IKEv2 requests.

/ip ipsec peer
add exchange-mode=ike2 name=ike2 passive=yes profile=ike2

Identity configuration

The identity menu allows to match specific remote peers and assign different configurations for each one of them. First, create a default identity, that will accept all peers, but will verify the peer’s identity with its certificate.

/ip ipsec identity
add auth-method=digital-signature certificate=server1 generate-policy=port-strict mode-config=ike2-conf peer=ike2 policy-template-group=ike2-policies

If the peer’s ID (ID_i) is not matching with the certificate it sends, the identity lookup will fail. See remote-id in the identities section.

For example, we want to assign a different mode config for user «A», who uses certificate «rw-client1» to authenticate itself to the server. First of all, make sure a new mode config is created and ready to be applied for the specific user.

/ip ipsec mode-config
add address=192.168.66.2 address-prefix-length=32 name=usr_A split-include=192.168.55.0/24 system-dns=no

It is possible to apply this configuration for user «A» by using the match-by=certificate parameter and specifying his certificate with remote-certificate.

/ip ipsec identity
add auth-method=digital-signature certificate=server1 generate-policy=port-strict match-by=certificate mode-config=usr_A peer=ike2 policy-template-group=ike2-policies remote-certificate=rw-client1

(Optional) Split tunnel configuration

Split tunneling is a method that allows road warrior clients to only access a specific secured network and at the same time send the rest of the traffic based on their internal routing table (as opposed to sending all traffic over the tunnel). To configure split tunneling, changes to mode config parameters are needed.

For example, we will allow our road warrior clients to only access the 10.5.8.0/24 network.

/ip ipsec mode-conf
set [find name="rw-conf"] split-include=10.5.8.0/24

It is also possible to send a specific DNS server for the client to use. By default, system-dns=yes is used, which sends DNS servers that are configured on the router itself in IP/DNS. We can force the client to use a different DNS server by using the static-dns parameter.

/ip ipsec mode-conf
set [find name="rw-conf"] system-dns=no static-dns=10.5.8.1

While it is possible to adjust the IPsec policy template to only allow road warrior clients to generate policies to network configured by split-include parameter, this can cause compatibility issues with different vendor implementations (see known limitations). Instead of adjusting the policy template, allow access to a secured network in IP/Firewall/Filter and drop everything else.

/ip firewall filter
add action=drop chain=forward src-address=192.168.77.0/24 dst-address=!10.5.8.0/24

Split networking is not a security measure. The client (initiator) can still request a different Phase 2 traffic selector.

Generating client certificates

To generate a new certificate for the client and sign it with a previously created CA.

/certificate
add common-name=rw-client1 name=rw-client1 key-usage=tls-client
sign rw-client1 ca=ca

PKCS12 format is accepted by most client implementations, so when exporting the certificate, make sure PKCS12 is specified.

/certificate
export-certificate rw-client1 export-passphrase=1234567890 type=pkcs12

A file named cert_export_rw-client1.p12 is now located in the routers System/File section. This file should be securely transported to the client’s device.

Typically PKCS12 bundle contains also a CA certificate, but some vendors may not install this CA, so a self-signed CA certificate must be exported separately using PEM format.

/certificate
export-certificate ca type=pem

A file named cert_export_ca.crt is now located in the routers System/File section. This file should also be securely transported to the client’s device.

PEM is another certificate format for use in client software that does not support PKCS12. The principle is pretty much the same.

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

Three files are now located in the routers Files section: cert_export_ca.crt, cert_export_rw-client1.crt and cert_export_rw-client1.key which should be securely transported to the client device.

Known limitations

Here is a list of known limitations by popular client software IKEv2 implementations.

  • Windows will always ignore networks received by split-include and request policy with destination 0.0.0.0/0 (TSr). When IPsec-SA is generated, Windows requests DHCP option 249 to which RouterOS will respond with configured split-include networks automatically.
  • Both Apple macOS and iOS will only accept the first split-include network.
  • Both Apple macOS and iOS will use the DNS servers from system-dns and static-dns parameters only when 0.0.0.0/0 split-include is used.
  • While some implementations can make use of different PFS group for phase 2, it is advised to use pfs-group=none under proposals to avoid any compatibility issues.

RouterOS client configuration

Import a PKCS12 format certificate in RouterOS.

/certificate import file-name=cert_export_RouterOS_client.p12 passphrase=1234567890

There should now be the self-signed CA certificate and the client certificate in the Certificate menu. Find out the name of the client certificate.

cert_export_RouterOS_client.p12_0 is the client certificate.

It is advised to create a separate Phase 1 profile and Phase 2 proposal configurations to not interfere with any existing IPsec configuration.

/ip ipsec profile
add name=ike2-rw
/ip ipsec proposal
add name=ike2-rw pfs-group=none

While it is possible to use the default policy template for policy generation, it is better to create a new policy group and template to separate this configuration from any other IPsec configuration.

/ip ipsec policy group
add name=ike2-rw
/ip ipsec policy
add group=ike2-rw proposal=ike2-rw template=yes

Create a new mode config entry with responder=no that will request configuration parameters from the server.

/ip ipsec mode-config
add name=ike2-rw responder=no

Lastly, create peer and identity configurations.

/ip ipsec peer
add address=2.2.2.2/32 exchange-mode=ike2 name=ike2-rw-client
/ip ipsec identity
add auth-method=digital-signature certificate=cert_export_RouterOS_client.p12_0 generate-policy=port-strict mode-config=ike2-rw peer=ike2-rw-client policy-template-group=ike2-rw

Verify that the connection is successfully established.

/ip ipsec
active-peers print
installed-sa print

Enabling dynamic source NAT rule generation

If we look at the generated dynamic policies, we see that only traffic with a specific (received by mode config) source address will be sent through the tunnel. But a router in most cases will need to route a specific device or network through the tunnel. In such case, we can use source NAT to change the source address of packets to match the mode config address. Since the mode config address is dynamic, it is impossible to create a static source NAT rule. In RouterOS, it is possible to generate dynamic source NAT rules for mode config clients.

For example, we have a local network 192.168.88.0/24 behind the router and we want all traffic from this network to be sent over the tunnel. First of all, we have to make a new IP/Firewall/Address list which consists of our local network

/ip firewall address-list
add address=192.168.88.0/24 list=local

When it is done, we can assign the newly created IP/Firewall/Address list to the mode config configuration.

/ip ipsec mode-config
set [ find name=ike2-rw ] src-address-list=local

Verify correct source NAT rule is dynamically generated when the tunnel is established.

[admin@MikroTik] > /ip firewall nat print 
Flags: X - disabled, I - invalid, D - dynamic 
0 D ;;; ipsec mode-config
chain=srcnat action=src-nat to-addresses=192.168.77.254 src-address-list=local dst-address-list=!local

Make sure the dynamic mode config address is not a part of a local network.

Windows client configuration

Open PKCS12 format certificate file on the Windows computer. Install the certificate by following the instructions. Make sure you select the Local Machine store location. You can now proceed to Network and Internet settings -> VPN and add a new configuration. Fill in the Connection name, Server name, or address parameters. Select IKEv2 under VPN type. When it is done, it is necessary to select «Use machine certificates». This can be done in Network and Sharing Center by clicking the Properties menu for the VPN connection. The setting is located under the Security tab.

Currently, Windows 10 is compatible with the following Phase 1 ( profiles) and Phase 2 ( proposals) proposal sets:

Phase 1
Hash Algorithm Encryption Algorithm DH Group
SHA1 3DES modp1024
SHA256 3DES modp1024
SHA1 AES-128-CBC modp1024
SHA256 AES-128-CBC modp1024
SHA1 AES-192-CBC modp1024
SHA256 AES-192-CBC modp1024
SHA1 AES-256-CBC modp1024
SHA256 AES-256-CBC modp1024
SHA1 AES-128-GCM modp1024
SHA256 AES-128-GCM modp1024
SHA1 AES-256-GCM modp1024
SHA256 AES-256-GCM modp1024
Phase 2
Hash Algorithm Encryption Algorithm PFS Group
SHA1 AES-256-CBC none
SHA1 AES-128-CBC none
SHA1 3DES none
SHA1 DES none
SHA1 none none

macOS client configuration

Open the PKCS12 format certificate file on the macOS computer and install the certificate in the «System» keychain. It is necessary to mark the CA certificate as trusted manually since it is self-signed. Locate the certificate macOS Keychain Access app under the System tab and mark it as Always Trust.

You can now proceed to System Preferences -> Network and add a new configuration by clicking the + button. Select Interface: VPN, VPN Type: IKEv2 and name your connection. Remote ID must be set equal to common-name or subjAltName of server’s certificate. Local ID can be left blank. Under Authentication Settings select None and choose the client certificate. You can now test the connectivity.

Currently, macOS is compatible with the following Phase 1 ( profiles) and Phase 2 ( proposals) proposal sets:

Phase 1
Hash Algorithm Encryption Algorithm DH Group
SHA256 AES-256-CBC modp2048
SHA256 AES-256-CBC ecp256
SHA256 AES-256-CBC modp1536
SHA1 AES-128-CBC modp1024
SHA1 3DES modp1024
Phase 2
Hash Algorithm Encryption Algorithm PFS Group
SHA256 AES-256-CBC none
SHA1 AES-128-CBC none
SHA1 3DES none

iOS client configuration

Typically PKCS12 bundle contains also a CA certificate, but iOS does not install this CA, so a self-signed CA certificate must be installed separately using PEM format. Open these files on the iOS device and install both certificates by following the instructions. It is necessary to mark the self-signed CA certificate as trusted on the iOS device. This can be done in Settings -> General -> About -> Certificate Trust Settings menu. When it is done, check whether both certificates are marked as «verified» under the Settings -> General -> Profiles menu.

You can now proceed to Settings -> General -> VPN menu and add a new configuration. Remote ID must be set equal to common-name or subjAltName of server’s certificate. Local ID can be left blank.

Currently, iOS is compatible with the following Phase 1 ( profiles) and Phase 2 ( proposals) proposal sets:

Phase 1
Hash Algorithm Encryption Algorithm DH Group
SHA256 AES-256-CBC modp2048
SHA256 AES-256-CBC ecp256
SHA256 AES-256-CBC modp1536
SHA1 AES-128-CBC modp1024
SHA1 3DES modp1024
Phase 2
Hash Algorithm Encryption Algorithm PFS Group
SHA256 AES-256-CBC none
SHA1 AES-128-CBC none
SHA1 3DES none

If you are connected to the VPN over WiFi, the iOS device can go into sleep mode and disconnect from the network.

Android (strongSwan) client configuration

Currently, there is no IKEv2 native support in Android, however, it is possible to use strongSwan from Google Play Store which brings IKEv2 to Android. StrongSwan accepts PKCS12 format certificates, so before setting up the VPN connection in strongSwan, make sure you download the PKCS12 bundle to your Android device. When it is done, create a new VPN profile in strongSwan, type in the server IP, and choose «IKEv2 Certificate» as VPN Type. When selecting a User certificate, press Install and follow the certificate extract procedure by specifying the PKCS12 bundle. Save the profile and test the connection by pressing on the VPN profile.

It is possible to specify custom encryption settings in strongSwan by ticking the «Show advanced settings» checkbox. Currently, strongSwan by default is compatible with the following Phase 1 ( profiles) and Phase 2 ( proposals) proposal sets:

Phase 1
Hash Algorithm Encryption Algorithm DH Group
SHA* AES-*-CBC modp2048
SHA* AES-*-CBC ecp256
SHA* AES-*-CBC ecp384
SHA* AES-*-CBC ecp521
SHA* AES-*-CBC modp3072
SHA* AES-*-CBC modp4096
SHA* AES-*-CBC modp6144
SHA* AES-*-CBC modp8192
SHA* AES-*-GCM modp2048
SHA* AES-*-GCM ecp256
SHA* AES-*-GCM ecp384
SHA* AES-*-GCM ecp521
SHA* AES-*-GCM modp3072
SHA* AES-*-GCM modp4096
SHA* AES-*-GCM modp6144
SHA* AES-*-GCM modp8192
Phase 2
Hash Algorithm Encryption Algorithm PFS Group
none AES-256-GCM none
none AES-128-GCM none
SHA256 AES-256-CBC none
SHA512 AES-256-CBC none
SHA1 AES-256-CBC none
SHA256 AES-192-CBC none
SHA512 AES-192-CBC none
SHA1 AES-192-CBC none
SHA256 AES-128-CBC none
SHA512 AES-128-CBC none
SHA1 AES-128-CBC none

Linux (strongSwan) client configuration

Download the PKCS12 certificate bundle and move it to /etc/ipsec.d/private directory.

Add exported passphrase for the private key to /etc/ipsec.secrets file where «strongSwan_client.p12» is the file name and «1234567890» is the passphrase.

: P12 strongSwan_client.p12 "1234567890"

Add a new connection to /etc/ipsec.conf file

conn "ikev2"
keyexchange=ikev2
ike=aes128-sha1-modp2048
esp=aes128-sha1
leftsourceip=%modeconfig
leftcert=strongSwan_client.p12
leftfirewall=yes
right=2.2.2.2
rightid="CN=2.2.2.2"
rightsubnet=0.0.0.0/0
auto=add

You can now restart (or start) the ipsec daemon and initialize the connection

$ ipsec restart
$ ipsec up ikev2

Road Warrior setup using IKEv2 with EAP-MSCHAPv2 authentication handled by User Manager (RouterOS v7)

This example explains how to establish a secure IPsec connection between a device connected to the Internet (road warrior client) and a device running RouterOS acting as an IKEv2 server and User Manager. It is possible to run User Manager on a separate device in network, however in this example both User Manager and IKEv2 server will be configured on the same device (Office).

RouterOS server configuration

Requirements

For this setup to work there are several prerequisites for the router:

  1. Router’s IP address should have a valid public DNS record — IP Cloud could be used to achieve this.
  2. Router should be reachable through port TCP/80 over the Internet — if the server is behind NAT, port forwarding should be configured.
  3. User Manager package should be installed on the router.

Generating Let’s Encrypt certificate

During the EAP-MSCHAPv2 authentication, TLS handshake has to take place, which means the server has to have a certificate that can be validated by the client. To simplify this step, we will use Let’s Encrypt certificate which can be validated by most operating systems without any intervention by the user. To generate the certificate, simply enable SSL certificate under the Certificates menu. By default the command uses the dynamic DNS record provided by IP Cloud, however a custom DNS name can also be specified. Note that, the DNS record should point to the router.

/certificate enable-ssl-certificate

If the certificate generation succeeded, you should see the Let’s Encrypt certificate installed under the Certificates menu.

/certificate print detail where name~"letsencrypt"

Configuring User Manager

First of all, allow receiving RADIUS requests from the localhost (the router itself):

/user-manager router
add address=127.0.0.1 comment=localhost name=local shared-secret=test

Enable the User Manager and specify the Let’s Encrypt certificate (replace the name of the certificate to the one installed on your device) that will be used to authenticate the users.

/user-manager
set certificate="letsencrypt_2021-04-09T07:10:55Z" enabled=yes

Lastly add users and their credentials that clients will use to authenticate to the server.

/user-manager user
add name=user1 password=password

Configuring RADIUS client

For the router to use RADIUS server for user authentication, it is required to add a new RADIUS client that has the same shared secret that we already configured on User Manager.

/radius
add address=127.0.0.1 secret=test service=ipsec

IPsec (IKEv2) server configuration

Add a new Phase 1 profile and Phase 2 proposal entries with pfs-group=none:

/ip ipsec profile
add name=ike2
/ip ipsec proposal
add name=ike2 pfs-group=none

Mode config is used for address distribution from IP/Pools.

/ip pool
add name=ike2-pool ranges=192.168.77.2-192.168.77.254
/ip ipsec mode-config
add address-pool=ike2-pool address-prefix-length=32 name=ike2-conf

Since that the policy template must be adjusted to allow only specific network policies, it is advised to create a separate policy group and template.

/ip ipsec policy group
add name=ike2-policies
/ip ipsec policy
add dst-address=192.168.77.0/24 group=ike2-policies proposal=ike2 src-address=0.0.0.0/0 template=yes

Create a new IPsec peer entry which will listen to all incoming IKEv2 requests.

/ip ipsec peer
add exchange-mode=ike2 name=ike2 passive=yes profile=ike2

Lastly create a new IPsec identity entry that will match all clients trying to authenticate with EAP. Note that generated Let’s Encrypt certificate must be specified.

/ip ipsec identity
add auth-method=eap-radius certificate="letsencrypt_2021-04-09T07:10:55Z" generate-policy=port-strict mode-config=ike2-conf peer=ike2 \
policy-template-group=ike2-policies

(Optional) Split tunnel configuration

Split tunneling is a method that allows road warrior clients to only access a specific secured network and at the same time send the rest of the traffic based on their internal routing table (as opposed to sending all traffic over the tunnel). To configure split tunneling, changes to mode config parameters are needed.

For example, we will allow our road warrior clients to only access the 10.5.8.0/24 network.

/ip ipsec mode-conf
set [find name="rw-conf"] split-include=10.5.8.0/24

It is also possible to send a specific DNS server for the client to use. By default, system-dns=yes is used, which sends DNS servers that are configured on the router itself in IP/DNS. We can force the client to use a different DNS server by using the static-dns parameter.

/ip ipsec mode-conf
set [find name="rw-conf"] system-dns=no static-dns=10.5.8.1

Split networking is not a security measure. The client (initiator) can still request a different Phase 2 traffic selector.

(Optional) Assigning static IP address to user

Static IP address to any user can be assigned by use of RADIUS Framed-IP-Address attribute.

/user-manager user
set [find name="user1"] attributes=Framed-IP-Address:192.168.77.100 shared-users=1

To avoid any conflicts, the static IP address should be excluded from the IP pool of other users, as well as shared-users should be set to 1 for the specific user.

(Optional) Accounting configuration

To keep track of every user’s uptime, download and upload statistics, RADIUS accounting can be used. By default RADIUS accounting is already enabled for IPsec, but it is advised to configure Interim Update timer that sends statistic to the RADIUS server regularly. If the router will handle a lot of simultaneous sessions, it is advised to increase the update timer to avoid increased CPU usage.

/ip ipsec settings
set interim-update=1m

Basic L2TP/IPsec setup

This example demonstrates how to easily set up an L2TP/IPsec server on RouterOS for road warrior connections (works with Windows, Android, iOS, macOS, and other vendor L2TP/IPsec implementations).

RouterOS server configuration

The first step is to enable the L2TP server:

/interface l2tp-server server
set enabled=yes use-ipsec=required ipsec-secret=mySecret default-profile=default

use-ipsec is set to required to make sure that only IPsec encapsulated L2TP connections are accepted.

Now what it does is enables an L2TP server and creates a dynamic IPsec peer with a specified secret.

[admin@MikroTik] /ip ipsec peer> print 
0 D address=0.0.0.0/0 local-address=0.0.0.0 passive=yes port=500 
auth-method=pre-shared-key secret="123" generate-policy=port-strict 
exchange-mode=main-l2tp send-initial-contact=yes nat-traversal=yes 
hash-algorithm=sha1 enc-algorithm=3des,aes-128,aes-192,aes-256 
dh-group=modp1024 lifetime=1d dpd-interval=2m dpd-maximum-failures=5 

Care must be taken if static IPsec peer configuration exists.

The next step is to create a VPN pool and add some users.

/ip pool add name=vpn-pool range=192.168.99.2-192.168.99.100

/ppp profile
set default local-address=192.168.99.1 remote-address=vpn-pool

/ppp secret
add name=user1 password=123
add name=user2 password=234

Now the router is ready to accept L2TP/IPsec client connections.

RouterOS client configuration

For RouterOS to work as L2TP/IPsec client, it is as simple as adding a new L2TP client.

/interface l2tp-client
add connect-to=1.1.1.1 disabled=no ipsec-secret=mySecret name=l2tp-out1 \
password=123 use-ipsec=yes user=user1

It will automatically create dynamic IPsec peer and policy configurations.

Troubleshooting/FAQ

Phase 1 Failed to get a valid proposal

[admin@MikroTik] /log> print
(..)
17:12:32 ipsec,error no suitable proposal found. 
17:12:32 ipsec,error 10.5.107.112 failed to get valid proposal. 
17:12:32 ipsec,error 10.5.107.112 failed to pre-process ph1 packet (side: 1, status 1). 
17:12:32 ipsec,error 10.5.107.112 phase1 negotiation failed. 
(..)

Peers are unable to negotiate encryption parameters causing the connection to drop. To solve this issue, enable IPSec to debug logs and find out which parameters are proposed by the remote peer, and adjust the configuration accordingly.

[admin@MikroTik] /system logging> add topics=ipsec,!debug
[admin@MikroTik] /log> print
(..)
17:21:08 ipsec rejected hashtype: DB(prop#1:trns#1):Peer(prop#1:trns#1) = MD5:SHA 
17:21:08 ipsec rejected enctype: DB(prop#1:trns#2):Peer(prop#1:trns#1) = 3DES-CBC:AES-CBC 
17:21:08 ipsec rejected hashtype: DB(prop#1:trns#2):Peer(prop#1:trns#1) = MD5:SHA 
17:21:08 ipsec rejected enctype: DB(prop#1:trns#1):Peer(prop#1:trns#2) = AES-CBC:3DES-CBC 
17:21:08 ipsec rejected hashtype: DB(prop#1:trns#1):Peer(prop#1:trns#2) = MD5:SHA 
17:21:08 ipsec rejected hashtype: DB(prop#1:trns#2):Peer(prop#1:trns#2) = MD5:SHA 
17:21:08 ipsec,error no suitable proposal found. 
17:21:08 ipsec,error 10.5.107.112 failed to get valid proposal. 
17:21:08 ipsec,error 10.5.107.112 failed to pre-process ph1 packet (side: 1, status 1). 
17:21:08 ipsec,error 10.5.107.112 phase1 negotiation failed. 
(..)

In this example, the remote end requires SHA1 to be used as a hash algorithm, but MD5 is configured on the local router. Setting before the column symbol (:) is configured on the local side, parameter after the column symbol (:) is configured on the remote side.

«phase1 negotiation failed due to time up» what does it mean?

There are communication problems between the peers. Possible causes include — misconfigured Phase 1 IP addresses; firewall blocking UDP ports 500 and 4500; NAT between peers not properly translating IPsec negotiation packets. This error message can also appear when a local-address parameter is not used properly. More information available here.

Random packet drops or connections over the tunnel are very slow, enabling packet sniffer/torch fixes the problem?

Problem is that before encapsulation packets are sent to Fasttrack/FastPath, thus bypassing IPsec policy checking. The solution is to exclude traffic that needs to be encapsulated/decapsulated from Fasttrack, see configuration example here.

How to enable ike2?

For basic configuration enabling ike2 is very simple, just change exchange-mode in peer settings to ike2.

fatal NO-PROPOSAL-CHOSEN notify message?

Remote peer sent notify that it cannot accept proposed algorithms, to find the exact cause of the problem, look at remote peers debug logs or configuration and verify that both client and server have the same set of algorithms.

I can ping only in one direction?

A typical problem in such cases is strict firewall, firewall rules allow the creation of new connections only in one direction. The solution is to recheck firewall rules, or explicitly accept all traffic that should be encapsulated/decapsulated.

Can I allow only encrypted traffic?

Yes, you can, see «Allow only IPsec encapsulated traffic» examples.

I enable IKEv2 REAUTH on StrongSwan and got the error ‘initiator did not reauthenticate as requested’

RouterOS does not support rfc4478, reauth must be disabled on StrongSwan.

IPSec (IP Security) — набор протоколов и алгоритмов для шифрования данных в IPv4 и IPv6 сетях. Звучит не сложно, но IPSec не устанавливает четких правил для шифрования трафика, вместо этого разработчики реализуют набор инструментов (протоколов и алгоритмов), используя которые администратор создает защищенный канал для данных.

Я хочу затронуть тему IPSec в RouterOS немного глубже простого HOWTO, с минимальным погружением в теорию и примерами по настройке и отладки IPSec. Это не гайд и без практики на тестовом стенде не рекомендуется приступать к настройке реальных туннелей и VPN серверов.

Преимущества и недостатки IPSec

Сильные стороны:

  • Работает на сетевом уровне модели OSI
  • Может шифровать исходный пакет целиком либо от транспортного уровня и выше
  • Присутствует механизм преодоления NAT
  • Большой набор алгоритмов шифрования и хеширования трафика, на выбор
  • IPSec — набор открытых, расширяемых стандартов
  • В случае с Mikrotik, не требует покупку дополнительных плат или лицензий

Слабые стороны:

  • Сложность
  • Различная терминология и инструменты конфигурации у различных вендеров
  • Использование сильных алгоритмов шифрования требует хорошие вычислительные мощности
  • Легко обнаруживается DPI

Протоколы в составе IPSec

Глобально, все протоколы, с которыми вы будете иметь дело при конфигурации, можно разделить на две группы: протоколы обмена ключами и протоколы защиты данных.

Протоколы обмена ключами (IKE)

Основная задача — аутентифицировать участников соединения и договориться о параметрах и ключах шифрования для защиты передаваемой информации.

  • IKE (Internet Key Exchange) — определен в 1998 году. Многие возможности (например преодоление NAT) были добавлены позже в виде дополнений и могут быть не реализованы у различных вендеров. Основой для согласования ключей является протокол ISAKMP.
  • IKEv2 (Internet Key Exchange version 2) — последняя редакция от 2014 года. Является развитием протокола IKE, в котором были решены некоторые проблемы, упрощен механизм согласования ключей, расширения (NAT-T, Keepalives, Mode Config) стали частью протокола.

На практике большая часть IPSec соединений реализуется с использованием IKE, в силу устаревшего оборудования, либо нежелания что-то менять у администраторов.

Протоколы защиты данных (ESP, AH)

Основная задача — защищать данные пользователя.

  • ESP (Encapsulating Security Payload) — шифрует и частично аутентифицирует передаваемые данные
  • AH (Authentication Header) — аутентифицирует пакет целиком (за исключением изменяемых полей), не шифрует данные, но позволяет убедиться, что пакет не был изменен при передачи по сети

Порядок установки IPSec соединения

Участников IPSec соединения принято называть пирами (peers), что показывает на их равнозначность в устанавливаемом соединении. Возможна конфигурация близкая к клиент-серверной, но при построении постоянных IPSec туннелей любой из пиров может быть инициализатором.

  1. Один из пиров инициализирует соединение IPSec
  2. Происходит обмен ключевой информацией, аутентификация пиров, согласование параметров подключения
  3. На основе полученной ключевой информации формируется вспомогательный шифрованный туннель
  4. Используя шифрованный туннель пиры определяют параметры шифрования данных и обмениваются информацией для генерации ключей
  5. Результатом работы предыдущей фазы является набор правил и ключи для защиты данных (SA)
  6. Периодически пиры производят обновление ключей шифрования

Одним из ключевых понятий в IPSec является SA (Security Association) — это согласованный пирами набор алгоритмов шифрования и хеширования информации, а также ключи шифрования.

Иногда можно встретить разделение на:

  • ISAKMP SA — параметры и ключи относящиеся к вспомогательному туннелю
  • Data SA (или просто SA) — параметры и ключи относящиеся к шифрованию трафика

Порядок работы протоколов согласования ключей

Протокол IKE может работать в двух режимах: основном (main) и агрессивном (aggressive), протокол IKEv2 содержит один режим.

IKE Main

Первая фаза состоит из шести пакетов:
1-2: Согласование параметров шифрования вспомогательного туннеля и различных опции IPSec
3-4: Обмен информацией для генерации секретного ключа
5-6: Аутентификация пиров используя вспомогательный шифрованный канал

Вторая фаза состоит из трех пакетов:
1-3: Используя шифрованный вспомогательный канал. Согласование параметров защиты трафика, обмен информацией для генерации секретного ключа

IKE Aggressive

Певая фаза состоит из трех пакетов:
1: Отправка предложения для установки вспомогательного шифрованного канала и информации для генерации секретного ключа
2: Ответ на предложение, информация для генерации секретного ключа, данные для аутентификации
3: Данные для аутентификации

Вторая фаза состоит из трех пакетов:
1-3: Используя шифрованный вспомогательный канал. Согласование параметров защиты трафика, обмен информацией для генерации секретного ключа

В агрессивном режиме инициатор отправляет только один набор параметров в предложении. Обмен информацией для аутентификации пиров происходит до установки защищенного вспомогательного туннеля. Агрессивный режим согласуется быстрее, но менее безопасен.

IKEv2

В IKEv2 фазы получили имена: IKE_SA_INIT и IKE_AUTH. Но если ниже по тексту я говорю про Phase1 и Phase2, то это относится и к фазам IKEv2.

Каждая фаза IKEv2 состоит из двух пакетов:
IKE_SA_INIT: Согласование параметров шифрования вспомогательного туннеля, обмен информацией для генерации секретного ключа

IKE_AUTH: используя шифрованный вспомогательный канал. Аутентификация пиров, согласование параметров защиты трафика, обмен информацией для генерации секретного ключа

Security Assotiations Database (SAD)

Результатом работы IKE (и IKEv2) являются Security Assotiations (SA), определяющие параметры защиты трафика и ключи шифрования. Каждый SA является однонаправленным и соединение IPSec содержит пару SA. Все SA хранятся в базе SAD и доступны администратору для просмотра и сброса.

Инкапсуляция данных

IPSec предоставляет два варианта инкапсуляции данных:

  • Транспортный режим — защищается только полезную нагрузку пакета, оставляя оригинальный заголовок. Для построения туннелей транспортный режим обычно используется в связке с ipip или gre, полезная нагрузка которых уже содержит весь исходный пакет.
  • Туннельный режим — полностью инкапсулирует исходный пакет в новый (по аналогии с gre или ipip). Но для туннельного ipsec не создается явного интерфейса в системе, это может быть проблемой если используется динамическая или сложная статическая маршрутизация.

Security Policy Database (SPD)

База правил, определяющих какой трафик необходимо подвергать шифрованию, протокол защиты данных, тип инкапсуляции и ряд других параметров.
Положение проверки пакета SPD можно отобразить на схеме Packet Flow.

Преодоление NAT

IPSec использует протоколы сетевого уровня для передачи данных, которые не может обработать NAT. Для решения проблемы используется протокол NAT-T (расширение в IKE и часть IKEv2). Суть NAT-T в дополнительной инкапсуляции пакетов IPSec в UDP пакеты, которые обрабатывает NAT.

IPSec в Mikrotik

IPSec доступен бесплатно на любом устройстве под управлением RouterOS с установленным пакетом Security.

Аппаратное шифрование

Для разгрузки CPU в некоторые модели маршрутизаторов MikroTik добавляют аппаратное ускорение шифрования, полный список можно найти на wiki.
Наиболее бюджетные варианты: RB750Gr3, RB3011, HAP AC^2.

Своими силами проверял скорость IPSec между двумя RB1100AHx2 и между двумя RB750Gr3.

Для достижения максимального результата на RB1100AHx2 необходимо:

  • Использовать 11 порт, напрямую подключенный к CPU и настроить одно ядро CPU для обработки трафика 11 порта
  • Использовать only-hardware-queues на интерфейсах, отключить RPS
  • Задействовать Layer3 FastPath (около 800mb/sec), либо исключить IPSec трафик из conntrack (около 700mb/sec)
    Без описанных манипуляций на самом медленном порту (ether13) удается получить ~170Mb/sec, на обычном ~400Mb/sec.

На RB750Gr3 без оптимизаций около 200Mb/sec.

Маршрутизаторы на одноядерных Qualcomm показывают результат 10-40mb/sec в зависимости от модели, оптимизаций и загруженности другими процессами.

Рекомендую ознакомиться с презентацией от сотрудника mikrotik, там затронуты темы оптимизации настроек для уменьшения нагрузки на CPU и увеличения скорости, которые я не стал добавлять в текст.

Различия 6.42.X и 6.43.X

В зависимости от используемой версии RouterOS меню конфигурации IPSec будет различаться.

В testing версии уже есть новые изменения, так что читайте Release Notes перед обновлением.

Конфигурация IPSec

Меню [IP]->[IPSec] не такое страшное, как кажется на первый взгляд. Из схемы видно, что основными пунктами конфигурации являются: Peers и Profiles.
Вкладки Remote Peers и Installed SAs являются информационными.

Peers и Peers Profiles

 

Конфигурация пиров IPSec для установки IKE соединения и создания вспомогательного защищенного туннеля.

Настройка удаленных пиров IPSec

Примечания:

  • Начиная с 6.43 RouterOS ругается при использовании PSK без дополнительной аутентификации. Если не хочется дополнительно настраивать ключи, сертификаты или xAuth можно перейти на IKEv2 или игнорировать предупреждение.
  • В качестве пиров можно указывать конкретные IP либо подсети (актуально для Client-Server VPN)
  • При наличии конфликтующих правил, для соединения с пиром будет использовано правило с более точной подсетью (по аналогии с routes)
  • Аутентификация xAuth и rsa key не работает в IKEv2
  • Для IKEv2 Mikrotik сделали свою реализацию xAuth не совместимую с другими платформами
  • Passive режим обычно используется для создания Client-Server VPN (L2TP/IPsec или IKEv2 mode config), но может быть полезен при подключении большого числа Site-to-Site туннелей к одной точке, для снижения паразитного трафика.
  • Если планируете использовать xAuth, то «сервер» должен быть passive. Пользователи для сервера создаются в [IPSec]->[Users]
  • При использовании Generate policy выбирайте режим port-strict

Настройка профилей (Proposals) для согласования Phase 1

Примечания:

  • Дополнительные опции для IKE стали частью IKEv2, настройки игнорируются
  • Соотношение групп DH с их номерами (номера групп используются у других вендеров)
  • При отправке предложений (Proposals) система сортирует пары алгоритм+группа dh от более стойких к менее стойким

Policies и Policy Proposals

Политики проверяют проходящие пакеты на соответствие условиям и применяют указанные действия. Если вернетесь к Packet flow, то блоки с IPSec Policy и есть сверка с политиками. В действиях задается: протокол защиты IPSec (ESP или AH), предложения для согласования SA, режим инкапсуляции.

Пакет проходит политики поочередно, пока не совпадет с условиями одной из них.

Настройка политик

Примчания:

  • Обычно не требуется указывать конкретный Src. и Dst. Port, но в целом возможность шифровать трафик отдельного приложения интересна
  • В списке Protocols представлены не все протоколы ip (например нет gre), можно указать номер нужного протокола вручную.
  • Шаблоны не являются политиками! Они используются, если в конфигурации пира установлено generate-policy
  • Что делать, если определенные SA для политики не были найдены. Раньше с L2TP/IPSec была проблема, когда несколько клиентов из-за одного NAT не могли подключиться (при использовании IKE), данный баг решается (при условии, что эти клиенты не windows) если установить level=unique. Иначе переходите на IKEv2
  • При настройке политик используйте [Safe mode], одно неловкое движение и вы рискуете потерять доступ к роутеру по Level3

Настройка предложений (Proposals) для согласования SA

Groups

Используются для связи шаблонов политик и пиров.

В одной из старых версий RouterOS был баг с нерабочей группой default.

Mode Config

 Отправка и получение параметров IP без использования дополнительных протоколов. Позволяет создавать самодостаточный Client-to-Server VPN только средствам IPSec.

Keys и Users

 Используются для расширенной аутентификации пиров.

Keys

Ключи RSA: генерация, импорт, экспорт. Не поддерживаются в IKEv2.

Users

База данных пользователей xAuth, для «сервера». Клиент указывает настройки xAuth в конфигурации пира. Возможно пересылать аутентификацию xAuth на RADIUS сервер.

Remote Peers

Список всех пиров устанавливающих и установивших вспомогательный туннель (Phase 1). Можно удалять пиров для обновления ключей вспомогательного туннеля.

Installed SAs

база данных SAD или список всех согласованных SA. Можно посмотреть используемые алгоритмы защиты данных и ключи.

Флаг Hardware AEAD указывает на использование аппаратного шифрования.

Администратор может сбросить SA, но только одновременно все одного типа (esp или ah).

IPSec и Firewall

В Firewall можно проверить соответствует трафик входящей или исходящей IPSec политики или нет. Очевидное применение — L2TP/IPSec, можно запретить установку L2TP соединений если трафик не был предварительно зашифрован.

Протоколы и порты, используемые в IPSec

  • IKE — UDP:500
  • IKEv2 — UDP:4500
  • NAT-T — UDP:4500
  • ESP — ipsec-esp(50)
  • AH — ipsec-ah(51)

IPSec и Endpoinds

А теперь о наболевшем…
На wiki mikrotik есть таблицы с алгоритмами хеширования и шифрования для: Windows, iOS, OS-X.

Про встроенный в android vpn клиент я информации не нашел, но в целом он работает с proposals от windows. Поддержки IKEv2 в Android нет, необходимо использовать StrongSwan.

Примеры конфигурации

Схема и базовая конфигурация для примеров с Site-to-Site туннелями:

#Mikrotik1

/ip address

add address=10.10.10.10/24 interface=ether1 network=10.10.10.0

add address=192.168.100.1/24 interface=ether2 network=192.168.100.0

/ip firewall nat

add action=masquerade chain=srcnat out-interface=ether1

/ip route

add distance=1 gateway=10.10.10.1 dst-address=0.0.0.0/0

#Mikrotik2

/ip address

add address=10.20.20.20/24 interface=ether1 network=10.20.20.0

add address=192.168.200.1/24 interface=ether2 network=192.168.200.0

/ip firewall nat

add action=masquerade chain=srcnat out-interface=ether1

/ip route

add distance=1 gateway=10.20.20.1 dst-address=0.0.0.0/0

IPSec в туннельном режиме

Пошаговая конфигурация:

  1. Создаем Proposals для IKE Phase1
  2. Создаем пира. Указываем адрес, proposals, режим обмена, ключ PSK. Я выбрал IKEv2, можно использовать main/agressive по желанию
  3. Создаем Proposals для SA
  4. Указываем подсети между которыми создаем туннель
  5. Указываем адреса SA, туннельный режим и proposals для шифрования трафика
  6. Редактируем правило NAT

Mikrotik1

Консольный вариант:

#1
/ip ipsec peer profile
add dh-group=modp2048 enc-algorithm=aes-128 hash-algorithm=sha256 name=ipsec-tunnel-ike nat-traversal=no

#2
/ip ipsec peer
add address=10.20.20.20/32 exchange-mode=ike2 profile=ipsec-tunnel-ike secret=test-ipsec

#3
/ip ipsec proposal
add auth-algorithms=sha256 enc-algorithms=aes-256-cbc name=ipsec-tunnel-sa

#4-5
/ip ipsec policy
add dst-address=192.168.200.0/24 proposal=ipsec-tunnel-sa sa-dst-address=10.20.20.20 sa-src-address=10.10.10.10 src-address=192.168.100.0/24 tunnel=yes

#6
/ip firewall nat
set 0 ipsec-policy=out,none

Mikrotik2

Консольный вариант:

 #1

/ip ipsec peer profile
add dh-group=modp2048 enc-algorithm=aes-128 hash-algorithm=sha256 name=ipsec-tunnel-ike nat-traversal=no

#2
/ip ipsec peer
add address=10.10.10.10/32 exchange-mode=ike2 profile=ipsec-tunnel-ike secret=test-ipsec

#3
/ip ipsec proposal
add auth-algorithms=sha256 enc-algorithms=aes-256-cbc name=tets-ipsec-sa

#4-5
/ip ipsec policy
add dst-address=192.168.100.0/24 proposal=tets-ipsec-sa sa-dst-address=10.10.10.10 sa-src-address=10.20.20.20 src-address=192.168.200.0/24 tunnel=yes

#6
/ip firewall nat
set 0 ipsec-policy=out,none

Причем тут NAT?

Для работы в туннельном режиме необходим фейковый маршрут до удаленной подсети, либо маршрут по умолчанию, иначе пакеты не пройдут дальше Routing decision. С первым вариантом проблем обычно нет, а вот с дефолтным маршрутом и Source NAT (первое и второе присутствует на подавляющем большинстве домашних и офисных маршрутизаторов) будут проблемы.

Вспоминаем Packet Flow. Пакеты проходят Source NAT раньше чем политики IPSec, правило с masquerade ничего не знает о том что трафик предназначен для отправки в «эфимерный» туннель и будет транслировать заголовки пакетов подлежащих отправки в IPSec, когда пакет с измененным заголовком попадет на проверку в Policies адрес источкина в заголовке не будет подходить под правило и пакет улетит на default route, который увидев адрес назначения из приватной сети вероятнее всего его отбросит.

Есть несколько решений проблемы:

  • Использование фейкового маршрута
  • Использование дополнительного accept правила перед SourceNAT
  • Подвергать src-nat только те пакеты, для которых нет политик IPSec (в примере)
  • Исключать трафик из connection tracking средствами RAW

  1. Видим соседа в Remote Peers
  2. Видим установленные SA (счетчики трафика не будут меняться, пока вы его не пустите)
  3. В политике статус Established и флаг (A)ctive

IPIP/IPSec

Предварительная настройка IPIP туннеля:

#Mikrotik1
#Настройка интерфейса ipip
/interface ipip
add allow-fast-path=no clamp-tcp-mss=no name=ipip-vpn remote-address=10.20.20.20
#Установка ip адреса на ipip интерфейс
/ip address
add address=10.30.30.1/30 interface=ipip-vpn
#Статический маршрут до удаленной подсети
/ip route
add distance=1 dst-address=192.168.200.0/24 gateway=10.30.30.2

#Mikrotik2
#Все аналогично, меняются только адреса и подсети
/interface ipip
add allow-fast-path=no clamp-tcp-mss=no name=ipip-vpn remote-address=10.10.10.10
/ip address
add address=10.30.30.2/30 interface=ipip-vpn
/ip route
add distance=1 dst-address=192.168.100.0/24 gateway=10.30.30.1

Пошаговая конфигурация IPSec:

  1. Создаем Proposals для IKE Phase1
  2. Создаем пира. Указываем адрес, proposals, режим обмена, ключ PSK
  3. Создаем Proposals для SA
  4. Указываем подсети между которыми создаем туннель
  5. Указываем адреса SA, тип трафика который будем шифровать и proposals

Mikrotik1

Консольный вариант:

#1
/ip ipsec peer profile
add dh-group=modp2048 enc-algorithm=aes-128 hash-algorithm=sha256 name=ipsec-tunnel-ike nat-traversal=no

#2
/ip ipsec peer
add address=10.20.20.20/32 exchange-mode=ike2 profile=ipsec-tunnel-ike secret=test-ipsec

#3
/ip ipsec proposal
add auth-algorithms=sha256 enc-algorithms=aes-256-cbc name=ipsec-tunnel-sa

#4-5
/ip ipsec policy
add dst-address=10.20.20.20/32 proposal=ipsec-tunnel-sa protocol=ipencap src-address=10.10.10.10/32 sa-dst-address=10.20.20.20 sa-src-address=10.10.10.10

Mikrotik2

Консольный вариант:

#1
/ip ipsec peer profile
add dh-group=modp2048 enc-algorithm=aes-128 hash-algorithm=sha256 name=ipsec-tunnel-ike nat-traversal=no

#2
/ip ipsec peer
add address=10.10.10.10/32 exchange-mode=ike2 profile=ipsec-tunnel-ike secret=test-ipsec

#3
/ip ipsec proposal
add auth-algorithms=sha256 enc-algorithms=aes-256-cbc name=tets-ipsec-sa

#4-5
/ip ipsec policy
add dst-address=10.10.10.10/32 proposal=tets-ipsec-sa protocol=ipencap src-address=10.20.20.20/32 sa-dst-address=10.10.10.10 sa-src-address=10.20.20.20

Для невнимательных, реальная разница конфигурации туннельного и транспортного режима в IPSec Policies:

Проверка соединения аналогична туннельному режиму.

 L2TP/IPSec

Предыдущие примеры хорошо подходят для создания постоянных VPN между двумя пирами, со статическими внешними IP адресами.

Если адрес одного из пиров динамический (и обычно находится за NAT’ом), необходимо использовать другую Client-to-Server VPN.

Предварительная конфигурация L2TP:

#Создание пула адресов для клиентов
/ip pool
add name=pool-l2tp ranges=192.168.77.10-192.168.77.20
#Создание профиля для клиентов
/ppp profile
add change-tcp-mss=yes local-address=192.168.77.1 name=l2tp-ipsec only-one=yes remote-address=pool-l2tp use-compression=no use-encryption=no use-mpls=no use-upnp=no
#Создание учетных записей
/ppp secret
add name=user1 password=test1 profile=l2tp-ipsec service=l2tp
add name=user2 password=test2 profile=l2tp-ipsec service=l2tp
add name=user3 password=test3 profile=l2tp-ipsec service=l2tp
#Включение сервера L2TP (без автонастройки ipsec)
/interface l2tp-server server
set authentication=chap,mschap2 default-profile=l2tp-ipsec enabled=yes

Почему я игнорирую автонастройку IPSec

В конфигурации ipip,gre,eoip,l2tp присутствует автонастройка ipsec соединения, по сути система создает динамические правила для Peers и Policies за вас, но во-первых — мы не ищем легких путей, во-вторых при обновлении с 6.42 на 6.43 автоматически созданные туннели ломались и не факт, что этого не повторится.

Пошаговая конфигурация IPSec:

  1. Создаем новую группу (можно использовать default)
  2. Создаем Proposals для IKE Phase1
  3. Создаем пира, точнее подсеть. Ругается на PSK ключ, но если мы имеем дело с windows в качестве клиента, то у нас на выбор: Сертификаты или PSK.
  4. Устанавливаем passive=yes и send-init-contact=no, в generate-policy=port-strict (принимать порт от клиента)
  5. Создаем Proposals для SA
  6. Создаем шаблон для генерации политик
  7. Указываем proposal для SA

Конфигурация Mikrotik

На скриншоте ошибка — указывать dst. port и src. port не нужно

Консольный вариант:

#1
/ip ipsec policy group
add name=l2tp-ipsec

#2
/ip ipsec peer profile
add dh-group=modp1024 enc-algorithm=aes-256 hash-algorithm=sha256 name=l2tp-ipsec-ike

#3-4
/ip ipsec peer
add address=0.0.0.0/0 generate-policy=port-strict passive=yes policy-template-group=l2tp-ipsec profile=l2tp-ipsec-ike secret=secret-ipsec-pass send-initial-contact=no

#5
/ip ipsec proposal
add auth-algorithms=sha256,sha1 enc-algorithms=aes-256-cbc,aes-128-cbc name=l2tp-ipsec-sa pfs-group=none

#6-7
/ip ipsec policy
add dst-address=0.0.0.0/0 group=l2tp-ipsec proposal=l2tp-ipsec-sa protocol=udp src-address=0.0.0.0/0 template=yes

Конфигурация firewall для создания L2TP подключений только после IPSec

/ip firewall filter
#Разрешаем IKE, NAT-T и ipsec-esp
add chain=input protocol=17 dst-port=500,4500 action=accept
add chain=input protocol=50 action=accept

#Разрешаем L2TP, только если есть политика ipsec для данного трафика
add chain=input protocol=17 dst-port=1701 ipsec-policy=in,ipsec action=accept
add chain=input protocol=17 dst-port=1701 action-drop

IKEv2 VPN

Вариант с L2TP является популярным, но благодаря mode config можно настроить VPN сервер используя только IPSec. Это перспективный тип VPN, но пока редко используемый, поэтому помимо конфигурации серверной части, я приведу пример настройки клиента strongSwan на android.

Конечно, не все так радужно. Большинство «пользовательских» ОС (в частности Windows и Android) согласны работать с таким VPN только при условии аутентификации по сертификатам или EAP.

Сертификаты — это мое слабое место, если кто в курсе как правильно сгенерировать самоподписные сертификат который windows импортирует и будет использовать в соединении — пишите в комментарии.

Предварительная генерация сертификатов:

#Root CA и сапомодпись
/certificate add name=ca common-name="IKEv2 CA" days-valid=6928
/certificate sign ca ca-crl-host=<IP роутера>

#Сертификат для сервера vpn
/certificate add common-name=<IP роутера> subject-alt-name=IP:<IP роутера> key-usage=tls-server name=vpn days-valid=6928

#Подпись серверного сертификата
/certificate sign vpn ca=ca

#Сертификат для клиента
#Клиенты с одним сертификатам не смогут работать одновременно, поэтому генерируйте по одному для каждого
#Для отмены доступа необходимо сделать Revoke клиентского сертификата
/certificate add common-name=client key-usage=tls-client name=client days-valid=6928

#Подпись клиентского сертификата
/certificate sign client ca=ca

Пошаговая конфигурация IKEv2 VPN:

  1. Создаем пул адресов для раздачи клиентам
  2. Создаем профиль mode config для раздачи параметров IP клиентам
  3. Создаем группы для связи Peers и шаблонов policies
  4. Создаем Proposals для IKE Phase1
  5. Создаем профиль для подключения пиров. Аутентификация через сертификаты, протокол IKEv2, пассивный режим
  6. Указываем профиль mode config, группу из 3 шага и включаем генерацию политик
  7. Создаем Proposals для SA
  8. Создаем шаблон для генерации политик
  9. Указываем Proposals для SA

Настройка Mikrotik

Консольный вариант:

#1
/ip pool
add name=pool-ike ranges=192.168.77.10-192.168.77.20

#2
/ip ipsec mode-config
add address-pool=pool-ike address-prefix-length=32 name=ikev2-vpn static-dns=77.88.8.8 system-dns=no

#3
/ip ipsec policy group
add name=ikev2-vpn

#4
/ip ipsec peer profile
add enc-algorithm=aes-256,aes-128 hash-algorithm=sha256 name=ikev2-vpn

#5-6
/ip ipsec peer
add address=0.0.0.0/0 auth-method=rsa-signature certificate=vpn exchange-mode=ike2 generate-policy=port-strict mode-config=ikev2-vpn passive=yes policy-template-group=ikev2-vpn profile=ikev2-vpn send-initial-contact=no

#7
/ip ipsec proposal
add auth-algorithms=sha256,sha1 enc-algorithms=aes-256-cbc,aes-128-cbc name=ikev2-vpn

#8-9
/ip ipsec policy
add dst-address=0.0.0.0/0 group=ikev2-vpn proposal=ikev2-vpn src-address= 0.0.0.0/0 template=yes

Конфигурация strongSwan на android.

Если соединение прошло успешно появятся: динамическая политика, запись в remote Peers и пара SA.

У RouterOS x86 demo лицензии нет ограничений на число IPSec туннелей, включая IKEv2 VPN. Можно развернуть RouterOS x86 demo (не путайте с RouterOS CHR free, там все грустно) на VPS и получить личный VPN сервер с минимальным напрягом по администрированию, без покупки лицензии на RouterOS или RouterOS CHR.

Пара слов про анализ логов IPSec

Логи в Mikrotik — отдельная история, да иногда они достаточно подробные для анализа проблемы, но отсутствие банальных возможностей: очистить, скопировать, найти вынуждает устанавливать отдельный syslog сервер.

Что касается IPSec, вот вариант быстрого анализа логов (оставляем только нужное на отдельной вкладке):

/system logging action
add memory-lines=100000 name=ipsec target=memory
/system logging
add action=ipsec topics=ipsec,error
add action=ipsec topics=ipsec,debug,!packet
add action=ipsec topics=ipsec,info

И пара примеров типичных проблем с конфигурацией IPSec:

Проблема согласования Proposals на Phase1

  1. Читаем сообщение об ошибке. Проблема при согласовании Proposals на первой фазе.
  2. Смотрим выше, роутер сам подсказывает что прислал пир, а что настроено локально

Проблема согласования proposals IKE_SA_INIT

В логах вы увидите примерно следующее:

Анализируем трафик

В запросе можно посмотреть proposals от пира:

В ответе видим, что не найдено подходящих proposals:

Проблема согласования Proposals для SA

Роутер подсказывает о ошибке proposals на phase2 и показывает что настроено локально, а что удаленно.

Проблема согласования Proposals IKE_AUTH

Видим, что произошло соединение и аутентификация пиров, но дальше ошибка proposals. В debug подробностей не увидите, в wireshark тоже (трафик IKE_AUTH зашифрован).

Ошибка аутентификации PSK

Для IKE:

Для IKEv2:

Неправильный режим IKE

Видим, что Phase1 рвется по таймауту, хотя пакеты между пирами ходят. Но размер входящего пакета значительно больше, если проанализировать через wireshark, то увидим, что удаленный пир использует aggressive mode.

Видим, что от нас пакеты отправляются на UDP:500, а приходят на UDP:4500 причем довольно крупные. Тут у удаленного пира стоит режим IKEv2.

И напоследок почитайте раздел troubleshooting из wiki. И весь материал про IPSec желателен для ознакомления, я описал только базовый набор инструментов и настроек.

Источник публикации

Время на прочтение
20 мин

Количество просмотров 116K

Добрый день, друзья. Не секрет, что многим из нас хоть раз, но пришлось столкнуться с необходимостью настройки VPN. Являясь активным читателем Хабра я заметил, что несмотря на обилие статей про IPSec, многим он всё равно представляется чем-то сложным и перегруженным. В данной статье я попытаюсь развеять данные мифы на примере собственной полностью рабочей конфигурации. В четырех примерах мы полностью пройдемся по настройке наиболее популярного решения под Linux (Strongswan) начиная от простого туннеля с аутентификацией сторон PSK-ключами до установки host-to-host соединения с аутентификацией обеих сторон на базе сертификатов от Let’s Encrypt. Интересно? Добро пожаловать под кат!

История вопроса

Изначально VPN планировался только для организации канала между мини-роутером родителей и домашним «подкроватным» сервером, по совместительству выступающим в роли маршрутизатора.

Спустя небольшой промежуток времени к этой компании из двух устройств добавился Keenetic.
Но единожды начав, остановиться оказалось сложно, и вскоре на схеме появились телефоны и ноутбук, которым захотелось скрыться от всевидящего рекламного ока MT_Free и прочих нешифрованных WiFi-сетей.

Потом у всеми любимого РКН наконец-то окреп банхаммер, которым он несказанно полюбил прилюдно размахивать во все стороны, и для нейтрализации его заботы о простых смертных пришлось

поддержать иностранный IT-сектор

приобрести VPS за рубежом.

К тому же некоей гражданке, внешне напоминающей Шапокляк, всюду бегающей со своим

ридикюлем

Пакетом и, вероятно, считающей что «Кто людям помогает — тот тратит время зря. Хорошими делами прославиться нельзя», захотелось тайком подглядывать в чужой трафик и брать его на карандаш. Придется тоже защищаться от такой непрошенной любви и VPN в данном случае именно то, что доктор прописал.

Подведем небольшой итог. Нужно было подобрать решение, которое в идеале способно закрыть сразу несколько поставленных задач:

  • Объединить сети между Linux-маршрутизаторами
  • Построить туннель между Linux и бытовым Keenetic
  • Дать доступ к домашним ресурсам и интернету носимым устройствам (телефоны, ноутбуки) из недоверенных сетей
  • Создать надежно зашифрованный туннель до удаленной VPS

Не стоит также забывать про прекрасный принцип KISS — Keep It Simple, Stupid. Чем меньше компонентов будет задействовано и чем проще настройка каждого из них — тем надежнее.

Обзор существующих решений

Коротко пройдемся по тому что есть сейчас:

PPTP

Дедушка Ленин всех протоколов. Умер, «разложился на плесень и на липовый мёд».

L2TP

Кто-то, кроме одного провайдера, это использует?

Wireguard

Проект развивается. Активно пилится. Легко создать туннель между двумя пирами, имеющими статический IP. В остальных случаях на помощь всегда готовы придти костыли, велосипеды с квадратными колёсами и синяя изолента, но это не наш путь.

OpenVPN

Плюсы:

  • Поддержка множества платформ — Windows, Linux, OpenWRT и её производные, Android
  • Стойкое шифрование и поддержка сертификатов.
  • Гибкость настройки.

И минусы:

  • Работа целиком и полностью в user-space.
  • Ограниченная поддержка со стороны домашних машрутизаторов — кривенько-косенько на Mikrotik (не умаляя остальных достоинств железок) и нормально в OpenWRT.
  • Сложности с настройкой мобильных клиентов: нужно скачивать, либо создавать свой инсталлятор, копировать куда-то конфиги.
  • В случае наличия нескольких туннелей ждут танцы с правкой systemd-юнитов на сервере.

OpenConnect (open-source реализация протокола Cisco Anyconnect)
Очень интересное решение о котором, к сожалению, довольно мало информации.

Плюсы:

  • Относительно широкая поддержка различных платформ — Windows, Android, Mac на базе родного приложения Cisco Anyconnect из магазина — идеальный вариант предоставить доступ ко внутренней сети носимым устройствам.
  • Стойкое шифрование, поддержка сертификатов, возможность подключения 2FA
  • Сам протокол полностью TLS-based (в отличие от OpenVPN, который легко детектится на 443 порту). Кроме TLS поддерживается и DTLS — во время установленного сеанса клиент может переключится на передачу данных через UDP и обратно.
  • Прекрасное сосуществование на одном порту как VPN, так и полноценного web-сервера при помощи sniproxy.
  • Простота настройки как сервера, так и клиентов.

Здесь тоже не обошлось без минусов:

  • Работа целиком и полностью в user-space.
  • TCP поверх TCP плохая идея.
  • Поддержки со стороны customer-grade оборудования нет.
  • Сложность установки туннелей между двумя Linux: теоретически можно, практически — лучше потратить время на что-то более полезное.
  • В случае наличия нескольких туннелей ждут танцы с несколькими конфигами и правкой systemd-юнитов.

Казалось бы тупик, но присмотревшись внимательнее и потратив немного времени на изучение я понял, что IPSec на базе IKEv2 способен заменить всё остальное.

IKEv2 IPSEC

Плюсы:

  • С появлением IKEv2 сам протокол стал проще в настройке, в сравнении с предыдущей версией, правда ценой потери обратной совместимости.
  • Благодаря стандартизации обеспечивается работа где угодно и на чём угодно — список можно вести до бесконечности. Linux, Mikrotik (в последних версиях RouterOS), OpenWRT, Android, iPhone. В Windows также есть нативная поддержка начиная с Windows 7.
  • Высокая скорость: обработка трафика полностью в kernel-space. User-space часть нужна только для установки параметров соединения и контроля работоспособности канала.
  • Возможность использовать несколько методов аутентификации: используя как PSK, так и сертификаты, причем в любых сочетаниях.
  • Несколько режимов работы: туннельный и транспортный. Чем они отличаются можно почитать в том числе и на Хабре.
  • Нетребовательность к настройкам промежуточных узлов: если в первой версии IKE были проблемы, вызванные NAT, то в IKEv2 есть встроенные механизмы для преодоления NAT и нативная фрагментация IKE-сообщений, позволяющая установить соединение на каналах с кривым MTU. Забегая вперед скажу, что на практике я еще ни разу не сталкивался с WiFi сетью, где бы клиенту не удалось установить соединение.

Минусы, впрочем, тоже есть:

  • Необходимо потратить немного времени на изучение и понять как это работает
  • Особенность, которая может сбить с толку новичка: IPSec, в отличие от привычных VPN решений, не создает сетевые интерфейсы. Задаются только политики обработки трафика, всё остальное разруливается средствами firewall.

Прежде чем приступить к настройке будем считать что читатель уже немного знаком с базовыми понятиями и терминами. В помощь новичку можно посоветовать статью с Википедии и сам Хабр, на котором уже достаточно интересных и полезных статей по данной тематике.

Приступаем к настройке

Определившись с решением приступаем к настройке. Схема сети в моем случае имеет следующий вид (убрал под спойлер)

Схема сети

ipsecgw.example.com — домашний сервер, являющийся центром сети. Внешний IP 1.1.1.1. Внутренняя сеть 10.0.0.0/23 и еще один адрес 10.255.255.1/30 для установки приватной BGP-сессии с VPS;
mama — Linux-роутер на базе маленького беззвучного неттопа, установленный у родителей. Интернет-провайдер выдает динамический IP-адрес. Внутренняя сеть 10.0.3.0/24;
keenetic — маршрутизатор Keenetic с установленным модулем IPSec. Интернет-провайдер выдает динамический IP-адрес. Внутренняя сеть 10.0.4.0/24;
road-warriors — переносные устройства, подключающиеся из недоверенных сетей. Адреса клиентам выдаются динамически при подключении из внутренного пула (10.1.1.0/24);
rkn.example.com — VPS вне юрисдикции уважаемого РКН. Внешний IP — 5.5.5.5, внутренний адрес 10.255.255.2/30 для установки приватной BGP-сессии.

Первый шаг. От простого к сложному: туннели с использованием pre-shared keys (PSK)

На обоих Linux-box устанавливаем необходимые пакеты:

sudo yum install strongswan

На обоих хостах открываем порты 500/udp, 4500/udp и разрешаем прохождение протокола ESP.
Правим файл /etc/strongswan/ipsec.secrects (на стороне хоста ipsecgw.example.com) и вносим следующую строку:

mama@router.home.local: PSK "Very strong PSK"

На второй стороне аналогично:

root@root.mama.local: PSK "Very strong PSK"

В данном случае в качестве ID выступает вымышленный адрес элестронной почты. Больше информации можно подчерпнуть на официальной вики.

Секреты сохранены, движемся дальше.

На хосте ipsecgw.example.com редактируем файл /etc/strongswan/ipsec.conf:

config setup //Настройки самого демона charon
    charondebug = "dmn 0, mgr 0, ike 0, chd 0, job 0, cfg 0, knl 0, net 0, asn 0, enc 0, lib 0, esp 0, tls 0, tnc 0, imc 0, imv 0, pts 0" //Отключаем избыточное логирование
conn %default //Общие настройки для всех соединений
    reauth = yes
    rekey = yes
    keyingtries = %forever
    keyexchange = ikev2 //Протокол обмена ключами для всех соединений - IKEv2
    dpdaction = hold
    dpddelay = 5s //Каждые 5 секунд шлем DPD (Dead Peer Detection) удаленной стороне 
    mobike = yes //Включаем Mobile IKE - пир может менять свой IP без необходимости переустановки тоннеля
conn mama //Описываем конкретное соединение
    left = %defaultroute //Left - наш пир. Директива %defaultroute указывает демону слушать на предмет установки IKE-сессии интрейфейс, котороый смотрит в default route
    right = %any //Удаленный пир может иметь любой IP-адрес
    authby = psk //Механизм проверки подлинности - используя секретый ключ
    leftid = mama@router.home.local //Наш ID, указанный в ipsec.secrets
    rightid = root@router.mama.local //ID удаленного пира
    leftsubnet = 10.0.0.0/23,10.1.1.0/24 
    rightsubnet = 10.0.3.0/24
    type = tunnel 
    ike = aes256-aes192-aes128-sha256-sha384-modp2048-modp3072-modp4096-modp8192,aes128gcm16-sha384-x25519!
    esp = aes256-aes192-aes128-sha256-sha384-modp2048-modp3072-modp4096-modp8192,aes128gcm16-sha256-sha384-x25519! 
    auto = add //При старте charon просто добавляем соединение и ждем подключения удаленной стороны

Аналогично редактируем на удаленном пире /etc/strongswan/ipsec.conf:

config setup
    charondebug = "dmn 0, mgr 0, ike 0, chd 0, job 0, cfg 0, knl 0, net 0, asn 0, enc 0, lib 0, esp 0, tls 0, tnc 0, imc 0, imv 0, pts 0"
conn %default
    reauth = yes
    rekey = yes
    keyingtries = %forever
    keyexchange = ikev2
    dpdaction = restart
    dpddelay = 5s
    mobike = yes
conn mama
    left = %defaultroute
    right = ipsecgw.example.com
    authby = psk
    leftid = root@router.mama.local
    rightid = mama@router.home.local
    leftsubnet = 10.0.3.0/24
    rightsubnet = 10.0.0.0/23,10.1.1.0/24
    type = tunnel
    ike = aes128gcm16-sha384-x25519!
    esp = aes128gcm16-sha384-x25519!
    auto = route

Если сравнить конфиги, то можно увидеть что они почти зеркальные, перекрёстно поменяны местами только определения пиров.

Директива auto = route заставляет charon установить ловушку для трафика, подпадающего в заданные директивами left/rightsubnet (traffic selectors). Согласование параметров туннеля и обмен ключами начнутся немедленно после появления трафика, попадающего под заданные условия.

На сервере ipsecgw.example.com в настройках firewall запрещаем маскарадинг для сети 10.0.3.0/24. Разрешаем форвардинг пакетов между 10.0.0.0/23 и 10.0.3.0/24 и наоборот. На удаленном узле выполняем аналогичные настройки, запретив маскарадинг для сети 10.0.0.0/23 и настроив форвардинг.

Рестартуем strongswan на обоих серверах и пробуем выполнить ping центрального узла:

sudo systemctl restart strongswan
ping 10.0.0.1

Убеждаемся что все работает:

sudo strongswan status
Security Associations (1 up, 0 connecting):
        mama[53]: ESTABLISHED 84 minutes ago, 1.1.1.1[mama@router.home.local]...2.2.2.2[root@router.mama.local]
        mama{141}:  INSTALLED, TUNNEL, reqid 27, ESP in UDP SPIs: c4eb45fe_i ca5ec6ca_o
        mama{141}:   10.0.0.0/23 10.1.1.0/24 === 10.0.3.0/24

Нелишним будет так же убедиться что в файле /etc/strongswan/strongswan.d/charon.conf на всех пирах параметр make_before_break установлен в значение yes. В данном случае демон charon, обслуживающий протокол IKEv2, при выполнении процедуры смены ключей не будет удалять текущую security association, а сперва создаст новую.

Шаг второй. Появление Keenetic

Приятной неожиданностью оказался встроенный IPSec VPN в официальной прошивке Keenetic. Для его активации достаточно перейти в Настройки компонентов KeeneticOS и добавить пакет IPSec VPN.

Готовим настройки на центральном узле, для этого:

Правим /etc/strongswan/ipsec.secrects и добавляем PSK для нового пира:

keenetic@router.home.local: PSK "Keenetic+PSK"

Правим /etc/strongswan/ipsec.conf и добавляем в конец еще одно соединение:

conn keenetic
    left = %defaultroute
    right = %any
    authby = psk
    leftid = keenetic@router.home.local
    rightid = root@router.keenetic.local
    leftsubnet = 10.0.0.0/23
    rightsubnet = 10.0.4.0/24
    type = tunnel
    ike = aes256-aes192-aes128-sha256-sha384-modp2048-modp3072-modp4096-modp8192,aes128gcm16-sha384-x25519!
    esp = aes256-aes192-aes128-sha256-sha384-modp2048-modp3072-modp4096-modp8192,aes128gcm16-sha256-sha384-x25519!
    auto = add

Со стороны Keenetic настройка выполняется в WebUI по пути: Интернет → Подключения →
Другие подключения
. Всё довольно просто.

Если планируется через тоннель гонять существенные объемы трафика, то можно попробовать включить аппаратное ускорение, которое поддерживается многими моделями. Включается командой crypto engine hardware в CLI. Для отключения и обработки процессов шифрования и хеширования при помощи инструкций CPU общего назначения — crypto engine software

После сохранения настроек рестрартуем strongswan и даём подумать полминуты Keenetic-у. После чего в терминале видим успешную установку соединения:

Все работает:

sudo strongswan status
Security Associations (2 up, 0 connecting):
    keenetic[57]: ESTABLISHED 39 minutes ago, 1.1.1.1[keenetic@router.home.local]...3.3.3.3[root@router.keenetic.local]
    keenetic{146}:  INSTALLED, TUNNEL, reqid 29, ESP SPIs: ca8f556e_i ca11848a_o
    keenetic{146}:   10.0.0.0/23 === 10.0.4.0/24
        mama[53]: ESTABLISHED 2 hours ago, 1.1.1.1[mama@router.home.local]...2.2.2.2[root@router.mama.local]
        mama{145}:  INSTALLED, TUNNEL, reqid 27, ESP in UDP SPIs: c5dc78db_i c7baafd2_o
        mama{145}:   10.0.0.0/23 10.1.1.0/24 === 10.0.3.0/24

Шаг третий. Защищаем мобильные устройства

После чтения стопки мануалов и кучи статей решено было остановиться на связке бесплатного сертификата от Let’s Encrypt для проверки подлинности сервера и классической авторизации по логину-паролю для клиентов. Тем самым мы избавляемся от необходимости поддерживать собственную PKI-инфраструктуру, следить за сроком истечения сертификатов и проводить лишние телодвижения с мобильными устройствами, устанавливая самоподписанные сертификаты в список доверенных.

Устанавливаем недостающие пакеты:

sudo yum install epel-release
sudo yum install certbot

Получаем standalone сертификат (не забываем предварительно открыть 80/tcp в настройках iptables):

sudo certbot certonly --standalone -d ipsecgw.example.com

После того как certbot завершил свою работу мы должны научить Strongswan видеть наш сертификат:

  • в директории /etc/strongswan/ipsec.d/cacerts создаем 2 символические ссылки: одну на корневое хранилище доверенных сертификатов в /etc/pki/tls/certs; и вторую с названием ca.pem, указывающую на /etc/letsencrypt/live/ipsecgw.example.com/chain.pem
  • В директории /etc/strongswan/ipsec.d/certs также создаются два симлинка: первый, с именем certificate.pem, ссылается на файл /etc/letsencrypt/live/ipsecgw.example.com/cert.pem. И второй, с именем fullchain.pem, ссылающийся на /etc/letsencrypt/live/ipsecgw.example.com/fullchain.pem
  • В директории /etc/strongswan/ipsec.d/private размещаем симлинк key.pem, указывающий на закрытый ключ, сгенерированный certbot и лежащий по пути /etc/letsencrypt/live/ipsecgw.example.com/privkey.pem

Добавляем в ipsec.secrets аутентификацию через RSA и связку логинов/паролей для новых пользователей:

ipsecgw.example.com     : RSA key.pem
username phone          : EAP "Q1rkz*qt"
username notebook       : EAP "Zr!s1LBz"

Перезапускаем Strongswan и при вызове sudo strongswan listcerts мы должны видеть информацию о сертификате:

List of X.509 End Entity Certificates

  subject:  "CN=ipsecgw.example.com"
  issuer:   "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3"
  validity:  not before May 23 19:36:52 2020, ok
             not after  Aug 21 19:36:52 2020, ok (expires in 87 days)
  serial:    04:c7:70:9c:a8:ce:57:cc:bf:6f:cb:fb:d3:a9:cf:06:b0:a8
  altNames:  ipsecgw.example.com
  flags:     serverAuth clientAuth
  OCSP URIs: http://ocsp.int-x3.letsencrypt.org
  certificatePolicies:
             2.23.140.1.2.1
             1.3.6.1.4.1.44947.1.1.1
             CPS: http://cps.letsencrypt.org

После чего описываем новое соединение в ipsec.conf:

conn remote-access
    dpddelay = 30s //Переопределяем частоту посылок DPD запросов, чтобы не сажать батарейку телефона
    left = %defaultroute
    leftid = "CN=ipsecgw.example.com"
    leftcert = fullchain.pem //При подключении отдаем клиенту наш сертификат с полной цепочкой доверия
    leftsendcert = always
    leftsubnet = 0.0.0.0/0 //Инструктируем клиента заворачивать весь трафик в туннель
    right = %any
    rightid = %any
    rightauth = eap-mschapv2 //Аутентифицируем пир, используя EAP-MSCHAP2
    rightsendcert = never
    eap_identity = %identity 
    rightsourceip = 10.1.1.0/24 //Strongswan будет выдавать адреса клиентам из данного пула
    rightdns = 10.0.0.1,10.0.0.3 //И отдавать указанные DNS
    type = tunnel
    ike = aes256-aes192-aes128-sha256-sha384-modp2048-modp3072-modp4096-modp8192,aes128gcm16-sha384-x25519!
    esp = aes256-aes192-aes128-sha256-sha384-modp2048-modp3072-modp4096-modp8192,aes128gcm16-sha256-sha384-x25519!
    auto = add //Добавляем соединение и ждем подключения удаленного пира
    dpdaction = restart //Рестартуем соединение, если пир перестал отвечать на DPD

Не забываем отредактировать файл /etc/sysconfig/certbot указав, что обновлять сертификат тоже будем как standalone, внеся в него CERTBOT_ARGS=»—standalone».

Так же не забываем включить таймер certbot-renew.timer и установить хук для перезапуска Strongswan в случае выдачи нового сертификата. Для этого либо размещаем простенький bash-скрипт в /etc/letsencrypt/renewal-hooks/deploy/, либо еще раз редактируем файл /etc/sysconfig/certbot.

Перезапускаем Strongswan, включаем в iptables маскарадинг для сети 10.1.1.0/24 и переходим к настройке мобильных устройств.

Android

Устанавливем из Google Play приложение Strongswan.

Запускаем и создаем новый

профиль

Сохраняем профиль, подключаемся и, спустя секунду, можем не переживать о том, что кто-то сможет подсматривать за нами.

Проверяем:

sudo strongswan statusall
Security Associations (3 up, 0 connecting):
remote-access[109]: ESTABLISHED 2 seconds ago, 1.1.1.1[CN=ipsecgw.example.com]...4.4.4.4[phone]
remote-access{269}:  INSTALLED, TUNNEL, reqid 55, ESP in UDP SPIs: c706edd1_i e5c12f1d_o
remote-access{269}:   0.0.0.0/0 ::/0 === 10.1.1.1/32
        mama[101]: ESTABLISHED 34 minutes ago, 1.1.1.1[mama@router.home.local]...2.2.2.2[root@router.mama.local]
        mama{265}:  INSTALLED, TUNNEL, reqid 53, ESP in UDP SPIs: c8c83342_i c51309db_o
        mama{265}:   10.0.0.0/23 10.1.1.0/24 === 10.0.3.0/24
    keenetic[99]: ESTABLISHED 36 minutes ago, 1.1.1.1[keenetic@router.home.local]...3.3.3.3[root@router.keenetic.local]
    keenetic{263}:  INSTALLED, TUNNEL, reqid 52, ESP SPIs: c3308f33_i c929d6f1_o
    keenetic{263}:   10.0.0.0/23 === 10.0.4.0/24

Windows

Windows актуальных версий приятно удивил. Вся настройка нового VPN происходит путем вызова двух командлетов PowerShell:

Add-VpnConnection -Name "IKEv2" -ServerAddress ipsecgw.example.com -TunnelType "IKEv2"
Set-VpnConnectionIPsecConfiguration -ConnectionName "IKEv2" -AuthenticationTransformConstants SHA256128 -CipherTransformConstants AES128 -EncryptionMethod AES128 -IntegrityCheckMethod SHA256 -PfsGroup PFS2048 -DHGroup Group14 -PassThru -Force

И еще одного, в случае если Strongswan настроен на выдачу клиентам IPv6 адреса (да, он это тоже умеет):

Add-VpnConnectionRoute -ConnectionName "IKEv2" -DestinationPrefix "2000::/3"

Часть четвертая, финальная. Прорубаем окно в Европу

Насмотревшись провайдерских заглушек «Сайт заблокирован по решению левой пятки пятого зампрокурора деревни Трудовые Мозоли Богозабытского уезда» появилась и жила себе одна маленькая неприметная VPS (с благозвучным доменным именем rkn.example.com) в тысяче километров от обезьянок, любящих размахивать банхаммером и блокировать сети размером /16 за раз. И крутилось на этой маленькой VPS прекрасное творение коллег из NIC.CZ под названием BIRD. Птичка первой версии постоянно умирала в панике от активности обезьянок с дубинками, забанивших на пике своей трудовой деятельности почти 4% интернета, уходя в глубокую задумчивость при реконфиге, поэтому была обновлена до версии 2.0.7. Если читателям будет интересно — опубликую статью по переходу с BIRD на BIRD2, в котором кардинально изменился формат конфига, но работать новая вервия стала намного быстрее и нет проблем с реконфигом при большом количестве маршрутов. А раз у нас используется протокол динамической маршрутизации, то должен быть и сетевой интерфейс, через который нужно роутить трафик. По умолчанию IPSec интерфейсов не создает, но за счет его гибкости мы можем воспользоваться классическими GRE-туннелями, которые и будем защищать в дальнейшем. В качестве бонуса — хосты ipsecgw.example.com и rkn.example.com будут аутентифицировать друга друга, используя самообновляемые сертификаты Lets Encrypt. Никаких PSK, только сертификаты, только хардкор, безопасности много не бывает.

Считаем что VPS подготовлена, Strongswan и Certbot уже установлены.

На хосте ipsecgw.example.com (его IP — 1.1.1.1) описываем новый интерфейс gif0:

sudo vi /etc/sysconfig/network-scripts/ifcfg-gif0
DEVICE="gif0"
MY_OUTER_IPADDR="1.1.1.1"
PEER_OUTER_IPADDR="5.5.5.5"
MY_INNER_IPADDR="10.255.255.1/30"
PEER_INNER_IPADDR="10.255.255.2/30"
TYPE="GRE"
TTL="64"
MTU="1442"
ONBOOT="yes"

Зеркально на хосте vps.example.com (его IP — 5.5.5.5):

sudo vi /etc/sysconfig/network-scripts/ifcfg-gif0
DEVICE="gif0"
MY_OUTER_IPADDR="5.5.5.5"
PEER_OUTER_IPADDR="1.1.1.1"
MY_INNER_IPADDR="10.255.255.2/30"
PEER_INNER_IPADDR="10.255.255.1/30"
TYPE="GRE"
TTL="64"
MTU="1442"
ONBOOT="yes"

Поднимаем интерфейсы, но поскольку в iptables нет правила, разрешающего GRE-протокол, трафик ходить не будет (что нам и надо, поскольку внутри GRE нет никакой защиты от любителей всяких законодательных «пакетов»).

Готовим VPS

Первым делом получаем еще один сертификат на доменное имя rkn.example.com. Создаем симлинки в /etc/strongswan/ipsec.d как описано в предыдущем разделе.

Правим ipsec.secrets, внося в него единственную строку:

rkn.example.com     : RSA key.pem

Правим ipsec.conf:

config setup
    charondebug = "dmn 0, mgr 0, ike 0, chd 0, job 0, cfg 0, knl 0, net 0, asn 0, enc 0, lib 0, esp 0, tls 0, tnc 0, imc 0, imv 0, pts 0"
    strictcrlpolicy = yes
conn %default
    reauth = yes
    rekey = yes
    keyingtries = %forever
    keyexchange = ikev2
    dpdaction = restart
    dpddelay = 5s
    mobike = yes
conn rkn
    left = %defaultroute
    right = ipsecgw.example.com
    authby = pubkey
    leftcert = fullchain.pem
    leftsendcert = always
    leftauth = pubkey
    rightauth = pubkey
    leftid = "CN=rkn.example.com"
    rightid = "CN=ipsecgw.example.com"
    rightrsasigkey = /etc/strongswan/ipsec.d/certs/ipsecgw.example.com.pem
    leftsubnet = %dynamic
    rightsubnet = %dynamic
    type = transport
    ike = aes256gcm16-sha384-x25519!
    esp = aes256gcm16-sha384-x25519!
    auto = route

На стороне хоста ipsecgw.example.com тоже добавляем в ipsec.conf в секцию setup параметр strictcrlpolicy = yes, включающий строгую проверку CRL. И описываем еще одно соединение:

conn rkn
    left = %defaultroute
    right = rkn.example.com
    leftcert = fullchain.pem
    leftsendcert = always
    leftauth = pubkey
    rightauth = pubkey
    rightrsasigkey = /etc/strongswan/ipsec.d/certs/rkn.exapmle.com.pem
    leftid = "CN=ipsecgw.example.com"
    rightid = "CN=rkn.example.com"
    leftsubnet = %dynamic
    rightsubnet = %dynamic
    type = transport
    ike = aes256gcm16-sha384-x25519!
    esp = aes256gcm16-sha384-x25519!
    auto = route
    dpdaction = restart

Конфиги почти зеркальные. Внимательный читатель мог сам уже обратить внимание на пару моментов:

  • left/rightsubnet = %dynamic — инструктирует Strongswan применять политики ко всем типам трафика между пирами
  • В каждом из конфигов указан параметр rightrsasigkey. Без него попытка установки IKE SA всегда будет оканчиваться ошибкой IKE AUTH ERROR в логе, поскольку Strongswan не сможет подписать сообщение без знания открытой части RSA-ключа удаленного пира. Для получения открытых ключей мы можем воспользоваться openssl. На каждом из хостов (ipsecgw и RKN) выполняем sudo /usr/bin/openssl rsa -in /etc/letsencrypt/live/ipsecgw.example.com/privkey.pem -pubout > ~/ipsecgw.example.com.pem и sudo /usr/bin/openssl rsa -in /etc/letsencrypt/live/rkn.example.com/privkey.pem -pubout > ~/rkn.example.com.pem, после чего при помощи scp перекрестно копируем их между серверами в расположения, указаные в конфиге

Не забываем настроить файрвол и автообновление сертификатов. После перезапуска Strongswan на обоих серверах, запустим ping удаленной стороны GRE-туннеля и увидим успешную установку соединения. На VPS (rkn):

sudo strongswan status
Routed Connections:
         rkn{1}:  ROUTED, TRANSPORT, reqid 1
         rkn{1}:   5.5.5.5/32 === 1.1.1.1/32
Security Associations (1 up, 0 connecting):
         rkn[33]: ESTABLISHED 79 minutes ago, 5.5.5.5[CN=rkn.example.com]...1.1.1.1[CN=ipsecgw.example.com]
         rkn{83}:  INSTALLED, TRANSPORT, reqid 1, ESP SPIs: cb4bc3bb_i c4c35a5a_o
         rkn{83}:   5.5.5.5/32 === 1.1.1.1/32

И на стороне хоста ipsecgw

под спойлером

Routed Connections:
         rkn{1}:  ROUTED, TRANSPORT, reqid 1
         rkn{1}:   1.1.1.1/32 === 5.5.5.5/32
Security Associations (4 up, 0 connecting):
remote-access[10]: ESTABLISHED 5 seconds ago, 1.1.1.1[CN=ipsecgw.example.com]...4.4.4.4[phone]
remote-access{12}:  INSTALLED, TUNNEL, reqid 7, ESP in UDP SPIs: c7a31be1_i a231904e_o
remote-access{12}:   0.0.0.0/0 === 10.1.1.1/32
    keenetic[8]: ESTABLISHED 22 minutes ago, 1.1.1.1[keenetic@router.home.local]...3.3.3.3[root@router.keenetic.local]
    keenetic{11}:  INSTALLED, TUNNEL, reqid 6, ESP SPIs: cfc1b329_i c01e1b6e_o
    keenetic{11}:   10.0.0.0/23 === 10.0.4.0/24
        mama[4]: ESTABLISHED 83 minutes ago, 1.1.1.1[mama@router.home.local]...2.2.2.2[root@router.mama.local]
        mama{8}:  INSTALLED, TUNNEL, reqid 3, ESP in UDP SPIs: c4a5451a_i ca67c223_o
        mama{8}:   10.0.0.0/23 10.1.1.0/24 === 10.0.3.0/24
         rkn[3]: ESTABLISHED 83 minutes ago, 1.1.1.1[CN=ipsecgw.example.com]...5.5.5.5[CN=rkn.example.com]
         rkn{7}:  INSTALLED, TRANSPORT, reqid 1, ESP SPIs: c4c35a5a_i cb4bc3bb_o
         rkn{7}:   1.1.1.1/32 === 5.5.5.5/32

Туннель установлен, пинги ходят, в tcpdump видно что между хостами ходит только ESP. Казалось бы можно радоваться. Но нельзя расслабляться не проверив всё до конца. Пробуем перевыпустить сертификат на VPS и…

Шеф, всё сломалось

Начинаем разбираться и натыкаемся на одну неприятную особенность прекрасного во всём остальном Let’s Encrypt — при любом перевыпуске сертификата меняется так же ассоциированный с ним закрытый ключ. Изменился закрытый ключ — изменился и открытый. На первый взгляд ситуация для нас безвыходная: если даже открытый ключ мы можем легко извлечь во время перевыпуска сертификата при помощи хука в certbot и передать его удаленной стороне через SSH, то непонятно как заставить удаленный Strongswan перечитать его. Но помощь пришла откуда не ждали — systemd умеет следить за изменениями файловой системы и запускать ассоциированные с событием службы. Этим мы и воспользуемся.

Создадим на каждом из хостов служебного пользователя keywatcher с максимально урезанными правами, сгенерируем каждому из них SSH-ключи и обменяемся ими между хостами.

На хосте ipsecgw.example.com создадим каталог /opt/ipsec-pubkey в котором разместим 2 скрипта.

sudo vi /opt/ipsec-pubkey/pubkey-copy.sh

#!/bin/sh
if [ ! -f /home/keywatcher/ipsecgw.example.com.pem ]; then
  /usr/bin/openssl rsa -in /etc/letsencrypt/live/ipsecgw.example.com/privkey.pem -pubout > /home/keywatcher/ipsecgw.example.com.pem;
  /usr/bin/chown keywatcher:keywatcher /home/keywatcher/ipsecgw.example.com.pem;
  /usr/bin/chmod 0600 /home/keywatcher/ipsecgw.example.com.pem;
  sudo -u keywatcher /usr/bin/scp /home/keywatcher/ipsecgw.example.com.pem rkn.example.com:/home/keywatcher/ipsecgw.example.com.pem;
  status=$?;
  if [ $status -eq 0 ]; then
    rm -f /home/keywatcher/ipsecgw.example.com.pem;
    logger "Public key ipsecgw.example.com.pem has been successfully uploaded to remote host";
  else
    logger "Public key ipsecgw.example.com.pem has not been uploaded to remote host due to error";
  fi
  else
    logger "Public key ipsecgw.example.com.pem already exist on /home/keywatcher directory, something went wrong";
fi
exit 0

sudo vi /opt/ipsec-pubkey/key-updater.sh

#!/bin/sh
/usr/bin/cp /home/keywatcher/rkn.example.com.pem /etc/strongswan/ipsec.d/certs/rkn.example.com.pem
/usr/bin/chown root:root /etc/strongswan/ipsec.d/certs/rkn.example.com.pem
/usr/bin/chmod 0600 /etc/strongswan/ipsec.d/certs/rkn.example.com.pem
logger "Public key of server rkn.example.com has been updated, restarting strongswan daemon to re-read it"
/usr/bin/systemctl restart strongswan
exit 0

На VPS (хосте rkn.example.com) аналогично создаем каталог с тем же именем, в котором тоже создаем аналогичные скрипты, изменяя только название ключа. Код, чтобы не загромождать статью, под

спойлером

sudo vi /opt/ipsec-pubkey/pubkey-copy.sh

#!/bin/sh
if [ ! -f /home/keywatcher/rkn.example.com.pem ]; then
  /usr/bin/openssl rsa -in /etc/letsencrypt/live/rkn.example.com/privkey.pem -pubout > /home/keywatcher/rkn.example.com.pem;
  /usr/bin/chown keywatcher:keywatcher /home/keywatcher/rkn.example.com.pem;
  /usr/bin/chmod 0600 /home/keywatcher/rkn.example.com.pem;
  sudo -u keywatcher /usr/bin/scp /home/keywatcher/rkn.example.com.pem ipsecgw.example.com:/home/keywatcher/rkn.example.com.pem;
  status=$?;
  if [ $status -eq 0 ]; then
    rm -f /home/keywatcher/rkn.example.com.pem;
    logger "Public key rkn.example.com.pem has been successfully uploaded to remote host";
  else
    logger "Public key rkn.example.com.pem has not been uploaded to remote host";
  fi
  else
    logger "Public key rkn.example.com.pem already exist on /home/keywatcher directory, something went wrong";
fi
exit 0

sudo vi /opt/ipsec-pubkey/key-updater.sh


#!/bin/bash
/usr/bin/cp /home/keywatcher/ipsecgw.example.com.pem /etc/strongswan/ipsec.d/certs/ipsecgw.example.com.pem;
/usr/bin/chown root:root /etc/strongswan/ipsec.d/certs/ipsecgw.example.com.pem
/usr/bin/chmod 0600 /etc/strongswan/ipsec.d/certs/ipsecgw.example.com.pem
logger "Public key of server ipsecgw.example.com has been updated, restarting connection"
/usr/bin/systemctl restart strongswan
exit 0

Скрипт pubkey-copy.sh нужен для извлечения открытой части ключа и копирования его удаленному хосту во время выпуска нового сертификата. Для этого в каталоге /etc/letsencrypt/renewal-hooks/deploy на обоих серверах создаем еще один микроскрипт:


#!/bin/sh
/opt/ipsec-pubkey/pubkey-copy.sh > /dev/null 2>&1
/usr/bin/systemctl restart strongswan
exit 0

Половина проблемы решена, сертификаты перевыпускаются, публичные ключи извлекаются и копируются между серверами и пришло время systemd с его path-юнитами.

На сервере ipsecgw.example.com в каталоге /etc/systemd/system создаем файл keyupdater.path

[Unit]
Wants=strongswan.service
[Path]
PathChanged=/home/keywatcher/rkn.example.com.pem
[Install]
WantedBy=multi-user.target

Аналогично на VPS хосте:

[Unit]
Wants=strongswan.service
[Path]
PathChanged=/home/keywatcher/ipsecgw.example.com.pem
[Install]
WantedBy=multi-user.target

И, напоследок, на каждом сервере создаем ассоциированную с данным юнитом службу, которая будет запускаться при выполнении условия (PathChanged) — изменении файла и его закрытии его после записи. Создаем файлы /etc/systemd/system/keyupdater.service и прописываем:

[Unit]
Description= Starts the IPSec key updating script
Documentation= man:systemd.service
[Service]
Type=oneshot
ExecStart=/opt/ipsec-pubkey/key-updater.sh
[Install]
WantedBy=multi-user.target

Не забываем перечитать конфигурации systemd при помощи sudo systemctl daemon-reload и назначить path-юнитам автозапуск через sudo systemctl enable keyupdater.path && sudo systemctl start keyupdater.path.

Как только удаленный хост запишет файл, содержащий публичный ключ, в домашний каталог пользователя keywatcher и файловый дескриптор будет закрыт, systemd автоматически запустит соответствующую службу, которая скопирует ключ в нужное расположение и перезапустит Strongswan. Туннель будет установлен, используя правильный открытый ключ второй стороны.

Можно выдохнуть и наслаждаться результатом.

Вместо заключения

Как мы только что увидели

чёрт

IPSec не так страшен, как его малюют. Всё, что было описано — полностью рабочая конфигурация, которая используется в настоящее время. Даже без особых знаний можно настроить VPN и надежно защитить свои данные.

Конечно за рамками статьи остались моменты настройки iptables, но и сама статья уже получилась и без того объемная и про iptables написано много.

Есть в статье и моменты, которые можно улучшить, будь-то отказ от перезапусков демона Strongswan, перечитывая его конфиги и сертификаты, но у меня не получилось этого добиться.

Впрочем и рестарты демона оказались не страшны: происходит потеря одного-двух пингов между пирами, мобильные клиенты тоже сами восстанавливают соединение.

Надеюсь коллеги в комментариях подскажут правильное решение.

IPsec (сокращение от IP Security) — набор протоколов для обеспечения защиты данных, передаваемых по межсетевому протоколу IP. Позволяет осуществлять подтверждение подлинности (аутентификацию), проверку целостности и/или шифрование IP-пакетов. IPsec также включает в себя протоколы для защищённого обмена ключами в сети Интернет. В основном, применяется для организации vpn-соединений.

История

Первоначально сеть Интернет была создана как безопасная среда передачи данных между военными. Так как с ней работал только определённый круг лиц, людей образованных и имеющих представления о политике безопасности, то явной нужды построения защищённых протоколов не было. Безопасность организовывалась на уровне физической изоляции объектов от посторонних лиц, и это было оправдано, когда к сети имело доступ ограниченное число машин. Однако, когда Интернет стал публичным и начал активно развиваться и разрастаться, такая потребность появилась.

И в 1994 году Совет по архитектуре Интернет (IAB) выпустил отчёт «Безопасность архитектуры Интернет». Он посвящался в основном способам защиты от несанкционированного мониторинга, подмены пакетов и управлению потоками данных. Требовалась разработка некоторого стандарта или концепции, способной решить эту проблему. В результате, появились стандарты защищённых протоколов, в числе которых и IPsec. Первоначально он включал в себя три базовые спецификации, описанные в документах (RFC1825, 1826 и 1827), однако впоследствии рабочая группа IP Security Protocol IETF пересмотрела их и предложила новые стандарты (RFC2401 — RFC2412), используемые и в настоящее время.

Стандарты

  • RFC 2401 (Security Architecture for the Internet Protocol) — Архитектура защиты для протокола IP.
  • RFC 2402 (IP Authentication header) — Аутентификационный заголовок IP.
  • RFC 2403 (The Use of HMAC-MD5-96 within ESP and AH) — Использование алгоритма хэширования MD-5 для создания аутентификационного заголовка.
  • RFC 2404 (The Use of HMAC-SHA-1-96 within ESP and AH) — Использование алгоритма хэширования SHA-1 для создания аутентификационного заголовка.
  • RFC 2405 (The ESP DES-CBC Cipher Algorithm With Explicit IV) — Использование алгоритма шифрования DES.
  • RFC 4303 (IP Encapsulating Security Payload (ESP)) — Шифрование данных.
  • RFC 2407 (The Internet IP Security Domain of Interpretation for ISAKMP) — Область применения протокола управления ключами.
  • RFC 2408 (Internet Security Association and Key Management Protocol (ISAKMP)) — Управление ключами и аутентификаторами защищённых соединений.
  • RFC 2409 (The Internet Key Exchange (IKE)) — Обмен ключами.
  • RFC 2410 (The NULL Encryption Algorithm and Its Use With IPsec) — Нулевой алгоритм шифрования и его использование.
  • RFC 2411 (IP Security Document Roadmap) — Дальнейшее развитие стандарта.
  • RFC 2412 (The OAKLEY Key Determination Protocol) — Проверка соответствия ключа.

Построение защищённого канала связи может быть реализовано на разных уровнях модели OSI. Так, например, популярный SSL-протокол работает на уровне представления, а PPTP — на сеансовом.

Уровни OSI Протокол защищённого канала
Прикладной уровень S/MIME
Уровень представления SSL, TLS
Сеансовый уровень PPTP
Транспортный уровень AH, ESP
Сетевой уровень IPsec
Канальный уровень
Физический уровень

В вопросе выбора уровня реализации защищённого канала несколько противоречивых аргументов: с одной стороны, за выбор верхних уровней говорит их независимость от вида транспортировки (выбора протокола сетевого и канального уровней), с другой стороны, для каждого приложения необходима отдельная настройка и конфигурация. Плюсом в выборе нижних уровней является их универсальность и наглядность для приложений, минусом — зависимость от выбора конкретного протокола (например, PPP или Ethernet).
Компромиссом в выборе уровня является IPsec: он располагается на сетевом уровне, используя самый распространённый протокол этого уровня — IP. Это делает IPsec более гибким, так что он может использоваться для защиты любых протоколов, базирующихся на TCP и UDP. В то же время, он прозрачен для большинства приложений.

IPsec является набором стандартов Интернет и своего рода «надстройкой» над IP-протоколом. Его ядро составляют три протокола:

  • Authentication Header (АН) обеспечивает целостность виртуального соединения (передаваемых данных), аутентификацию источника информации и функцию по предотвращению повторной передачи пакетов
  • Encapsulating Security Payload (ESP) обеспечивает конфиденциальность (шифрование) передаваемой информации, ограничение потока конфиденциального трафика. Кроме этого, он может исполнять функции AH: обеспечить целостность виртуального соединения (передаваемых данных), аутентификацию источника информации и функцию по предотвращению повторной передачи пакетов. При применении ESP в обязательном порядке должен указываться набор услуг по обеспечению безопасности: каждая из его функций может включаться опционально.
  • Internet Security Association and Key Management Protocol (ISAKMP) — протокол, используемый для первичной настройки соединения, взаимной аутентификации конечными узлами друг друга и обмена секретными ключами. Протокол предусматривает использование различных механизмов обмена ключами, включая задание фиксированных ключей, использование таких протоколов, как Internet Key Exchange, Kerberized Internet Negotiation of Keys (RFC 4430) или записей DNS типа IPSECKEY (RFC 4025).

Также одним из ключевых понятий является Security Association (SA). По сути, SA является набором параметров, характеризующим соединение. Например, используемые алгоритм шифрования и хэш-функция, секретные ключи, номер пакета и др.

Туннельный и транспортный режимы

IPsec может функционировать в двух режимах: транспортном и туннельном.

В транспортном режиме шифруются (или подписываются) только данные IP-пакета, исходный заголовок сохраняется. Транспортный режим, как правило, используется для установления соединения между хостами. Он может также использоваться между шлюзами для защиты туннелей, организованных каким-нибудь другим способом (см., например, L2TP).

В туннельном режиме шифруется весь исходный IP-пакет: данные, заголовок, маршрутная информация, а затем он вставляется в поле данных нового пакета, то есть происходит инкапсуляция. Туннельный режим может использоваться для подключения удалённых компьютеров к виртуальной частной сети или для организации безопасной передачи данных через открытые каналы связи (например, Интернет) между шлюзами для объединения разных частей виртуальной частной сети.

Режимы IPsec не являются взаимоисключающими. На одном и том же узле некоторые SA могут использовать транспортный режим, а другие — туннельный.

Security Association

Для начала обмена данными между двумя сторонами необходимо установить соединение, которое носит название SA (Security Association). Концепция SA фундаментальна для IPsec, собственно, является его сутью. Она описывает, как стороны будут использовать сервисы для обеспечения защищённого общения. Соединение SA является симплексным (однонаправленным), поэтому для взаимодействия сторон необходимо установить два соединения. Стоит также отметить, что стандарты IPsec позволяют конечным точкам защищённого канала использовать как одно SA для передачи трафика всех взаимодействующих через этот канал хостов, так и создавать для этой цели произвольное число безопасных ассоциаций,
например, по одной на каждое TCP-соединение. Это дает возможность выбирать нужную степень детализации защиты. Установка соединения начинается со взаимной аутентификации сторон. Далее происходит выбор параметров (будет ли осуществляться аутентификация, шифрование, проверка целостности данных) и необходимого протокола (AH или ESP) передачи данных. После этого выбирается конкретные алгоритмы (например, шифрования, хэш-функция) из нескольких возможных схем, некоторые из которых определены стандартом (для шифрования — DES, для хэш-функций — MD5 либо SHA-1), другие добавляются производителями продуктов, использующих IPsec (например Triple DES, Blowfish, CAST).

Security Associations Database

Все SA хранятся в базе данных SAD (Security Associations Database) IPsec-модуля. Каждое SA имеет уникальный маркер, состоящий из трёх элементов:

  • индекса параметров безопасности (Security Parameters Index, SPI)
  • IP-адреса назначения
  • идентификатора протокола безопасности (ESP или AH)

IPsec-модуль, имея эти три параметра, может отыскать в SAD запись о конкретном SA. В список компонентов SA входят:

Последовательный номер
32-битовое значение, которое используется для формирования поля Sequence Number в заголовках АН и ESP.
Переполнение счетчика порядкового номера
Флаг, который сигнализирует о переполнении счетчика последовательного номера.
Окно для подавления атак воспроизведения
Используется для определения повторной передачи пакетов. Если значение в поле Sequence Number не попадает в заданный диапазон, то пакет уничтожается.
Информация AH
используемый алгоритм аутентификации, необходимые ключи, время жизни ключей и другие параметры.
Информация ESP
алгоритмы шифрования и аутентификации, необходимые ключи, параметры инициализации (например, IV), время жизни ключей и другие параметры
Режим работы IPsec
туннельный или транспортный
Время жизни SA
Задано в секундах или байтах информации, проходящих через туннель. Определяет длительность существования SA, при достижении этого значения текущее SA должно завершиться, при необходимости продолжить соединение, устанавливается новое SA.
MTU
Максимальный размер пакета, который можно передать по виртуальному каналу без фрагментации.

Каждый протокол (ESP/AH) должен иметь свой собственный SA для каждого направления, таким образом, связка AH+ESP требует для дуплексного канала наличия четырёх SA. Все эти данные располагаются в SAD.

В SAD содержатся:

  • AH: алгоритм аутентификации.
  • AH: секретный ключ для аутентификации
  • ESP: алгоритм шифрования.
  • ESP: секретный ключ шифрования.
  • ESP: использование аутентификации (да/нет).
  • Параметры для обмена ключами
  • Ограничения маршрутизации
  • Политика IP-фильтрации

Security Policy Database

Помимо базы данных SAD, реализации IPsec поддерживают базу данных SPD (Security Policy Database — база данных политики безопасности). SPD служит для соотнесения приходящих IP-пакетов с правилами обработки для них. Записи в SPD состоят из двух полей. В первом хранятся характерные признаки пакетов, по которым можно выделить тот или иной поток информации. Эти поля называются селекторами. Примеры селекторов, которые содержатся в SPD:

  • IP-адрес места назначения
  • IP-адрес отправителя
  • Имя пользователя в формате DNS или X.500
  • Порты отправителя и получателя

Второе поле в SPD содержит политику защиты, соответствующую данному потоку пакетов. Селекторы используются для фильтрации исходящих пакетов с целью поставить каждый пакет в соответствие с определенным SA. Когда поступает пакет, сравниваются значения соответствующих полей в пакете (селекторные поля) с теми, которые содержатся в SPD. При нахождении совпадения в поле политики защиты содержится информация о том, как поступать с данным пакетом: передать без изменений, отбросить или обработать. В случае обработки, в этом же поле содержится ссылка на соответствующую запись в SAD. Затем определяется SA для пакета и сопряжённый с ней индекс параметров безопасности (SPI), после чего выполняются операции IPsec (операции протокола AH или ESP).
Если пакет входящий, то в нём сразу содержится SPI — проводится соответствующая обработка.

Authentication Header format

Offsets Octet16 0 1 2 3
Octet16 Bit10 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
0 0 Next Header Payload Len Reserved
4 32 Security Parameters Index (SPI)
8 64 Sequence Number
C 96 Integrity Check Value (ICV)
Тип следующего заголовка (8 bits)
Тип заголовка протокола, идущего после заголовка AH. По этому полю приёмный IP-sec модуль узнает о защищаемом протоколе верхнего уровня. Значения этого поля для разных протоколов можно посмотреть в RFC 1700.
Длина содержимого (8 bits)
Это поле определяет общий размер АН-заголовка в 32-битовых словах, минус 2. Несмотря на это, при использовании IPv6 длина заголовка должна быть кратна 8 байтам.
Зарезервировано (16 bits)
Зарезервировано. Заполняется нулями.
Индекс параметров системы безопасности (32 bits)
Индекс параметров безопасности. Значение этого поля вместе с IP-адресом получателя и протоколом безопасности (АН-протокол), однозначно определяет защищённое виртуальное соединение (SA) для данного пакета. Диапазон значений SPI 1…255 зарезервирован IANA.
Порядковый номер(32 bits)
Последовательный номер. Служит для защиты от повторной передачи. Поле содержит монотонно возрастающее значение параметра. Несмотря на то, что получатель может отказаться от услуги по защите от повторной передачи пакетов, оно является обязательным и всегда присутствует в AH-заголовке. Передающий IPsec-модуль всегда использует это поле, но получатель может его и не обрабатывать.
Данные аутентификации
Цифровая подпись. Служит для аутентификации и проверки целостности пакета. Должна быть дополнена до размера, кратного 8-байтам для IPv6, и 4-байтам для IPv4.

Протокол AH используется для аутентификации, то есть для подтверждения того, что мы связываемся именно с тем, с кем предполагаем, и что данные, которые мы получаем, не искажены при передаче.

Обработка выходных IP-пакетов

Если передающий IPsec-модуль определяет, что пакет связан с SA, которое предполагает AH-обработку, то он начинает обработку. В зависимости от режима (транспортный или режим туннелирования) он по-разному вставляет AH-заголовок в IP-пакет. В транспортном режиме AH-заголовок располагается после заголовка протокола IP и перед заголовками протоколов верхнего уровня (Обычно, TCP или UDP). В режиме туннелирования весь исходный IP-пакет обрамляется сначала заголовком AH, затем заголовком IP-протокола. Такой заголовок называется внешним, а заголовок исходного IP-пакета- внутренним. После этого передающий IPsec-модуль должен сгенерировать последовательный номер и записать его в поле Sequence Number. При установлении SA последовательный номер устанавливается в 0, и перед отправкой каждого IPsec-пакета увеличивается на единицу. Кроме того, происходит проверка- не зациклился ли счетчик. Если он достиг своего максимального значения, то он снова устанавливается в 0. Если используется услуга по предотвращению повторной передачи, то при достижении счетчика своего максимального значения, передающий IPsec-модуль переустанавливает SA. Таким образом обеспечивается защита от повторной посылки пакета — приёмный IPsec-модуль будет проверять поле Sequence Number, и игнорировать повторно приходящие пакеты. Далее происходит вычисление контрольной суммы ICV. Надо заметить, что здесь контрольная сумма вычисляется с применением секретного ключа, без которого злоумышленник сможет заново вычислить хэш, но не зная ключа, не сможет сформировать правильную контрольную сумму. Конкретные алгоритмы, использующиеся для вычисления ICV, можно узнать из RFC 4305. В настоящее время могут применяться, например, алгоритмы HMAC-SHA1-96 или AES-XCBC-MAC-96. Протокол АН вычисляет контрольную сумму (ICV) по следующим полям IPsec-пакета:

  • поля IP-заголовка, которые не были подвержены изменениям в процессе транслирования, или определены как наиболее важные
  • АН-заголовок (Поля: «Next Header», «Payload Len, «Reserved», «SPI», «Sequence Number», «Integrity Check Value». Поле «Integrity Check Value» устанавливается в 0 при вычислении ICV
  • данные протокола верхнего уровня
Если поле может изменяться в процессе транспортировки, то его значение устанавливается в 0 перед вычислением ICV. Исключения составляют поля, которые могут изменяться, но значение которых можно предугадать при приёме. При вычислении ICV они не заполняются нулями. Примером изменяемого поля может служить поле контрольной суммы, примером изменяемого, но предопределенного может являться IP-адрес получателя. Более подробное описание того, какие поля как учитываются при вычислении ICV, можно найти в стандарте RFC 2402.

Обработка входных IP-пакетов

После получения пакета, содержащего сообщение АН-протокола, приёмный IPsec-модуль ищет соответствующее защищённое виртуальное соединение (SA) SAD (Security Associations Database), используя IP-адрес получателя, протокол безопасности (АН) и индекс SPI. Если соответствующее SA не найдено, пакет уничтожается. Найденное защищённое виртуальное соединение (SA) указывает на то, используется ли услуга по предотвращению повторной передачи пакетов, то есть на необходимость проверки поля Sequence Number. Если услуга используется, то поле проверяется. При этом используется метод скользящего окна для ограничения буферной памяти, требуемый для работы протоколу. Приёмный IPsec-модуль формирует окно с шириной W (обычно W выбирается равным 32 или 64 пакетам). Левый край окна соответствует минимальному последовательному номеру (Sequence Number) N правильно принятого пакета. Пакет с полем Sequence Number, в котором содержится значение, начиная от N+1 и заканчивая N+W, принимается корректно. Если полученный пакет оказывается по левую границу окна- он уничтожается. Затем приёмный IPsec-модуль вычисляет ICV по соответствующим полям принятого пакета, используя алгоритм аутентификации, который он узнает из записи об SA, и сравнивает полученный результат со значением ICV, расположенным в поле «Integrity Check Value». Если вычисленное значение ICV совпало с принятым, то пришедший пакет считается действительным и принимается для дальнейшей IP-обработки. Если проверка дала отрицательный результат, то принятый пакет уничтожается.

Encapsulating Security Payload

Encapsulating Security Payload format

Offsets Octet16 0 1 2 3
Octet16 Bit10 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
0 0 Security Parameters Index (SPI)
4 32 Sequence Number
8 64 Payload data
   
  Padding (0-255 octets)  
  Pad Length Next Header
Integrity Check Value (ICV)
Security Parameters Index (32 bits)
Индекс параметров безопасности (аналогичен соответствующему полю AH). Значение этого поля вместе с IP-адресом получателя и протоколом безопасности (ESP-протокол), однозначно определяет защищённое виртуальное соединение (SA) для данного пакета. Диапазон значений SPI 1…255 зарезервирован IANA для последующего использования.
Sequence Number (32 bits)
Последовательный номер (аналогичен соответствующему полю AH). Служит для защиты от повторной передачи. Поле содержит монотонно возрастающее значение параметра. Несмотря на то, что получатель может и отказаться от услуги по защите от повторной передачи пакетов, оно всегда присутствует в ESP-заголовке. Отправитель (передающий IPsec-модуль) должен всегда использовать это поле, но получатель может и не нуждаться в его обработке.
Payload data (variable)
Это поле содержит данные (в зависимости от выбора режима — туннельного или транспортного, здесь может находиться либо весь исходный инкапсулированный пакет, либо лишь его данные) в соответствии с полем «Next Header». Это поле является обязательным и состоит из целого числа байтов. Если алгоритм, который используется для шифрования этого поля, требует данных для синхронизации криптопроцессов (например, вектор инициализации — «Initialization Vector»), то это поле может содержать эти данные в явном виде.
Padding (0-255 octets)
Дополнение. Необходимо, например, для алгоритмов, которые требуют, чтобы открытый текст был кратен некоторому числу байтов), например, размеру блока для блочного шифра.
Pad Length (8 bits)
Размер дополнения (в байтах).
Next Header (8 bits)
Это поле определяет тип данных, содержащихся в поле «Payload data».
Integrity Check Value
Контрольная сумма. Служит для аутентификации и проверки целостности пакета. Должна быть кратна 8-байтам для IPv6, и 4-байтам для IPv4.

Обработка выходных IPsec-пакетов

Если передающий IPsec-модуль определяет, что пакет связан с SA, которое предполагает ESP-обработку, то он начинает обработку. В зависимости от режима(транспортный или режим туннелирования) исходный IP-пакет обрабатывается по-разному. В транспортном режиме передающий IPsec-модуль осуществляет процедуру обрамления протокола верхнего уровня (например, TCP или UDP), используя для этого ESP-заголовок (поля Security Parameters Index и Sequence Number заголовка) и ESP-концевик (остальные поля заголовка, следующие за полем данных — Payload data), не затрагивая при этом заголовок исходного IP-пакета. В режиме туннелирования IP-пакет обрамляется ESP-заголовком и ESP-концевиком (инкапсуляция), после чего обрамляется внешним IP-заголовком (который может не совпадать с исходным — например, если IPsec модуль установлен на шлюзе).

Далее производится шифрование- в транспортном режиме шифруется только сообщение протокола выше лежащего уровня (то есть все, что находилось после IP-заголовка в исходном пакете), в режиме туннелирования- весь исходный IP-пакет. Передающий IPsec-модуль из записи о SA определяет алгоритм шифрования и секретный ключ. Стандарты IPsec разрешают использование алгоритмов шифрования Triple DES, AES и Blowfish, если их поддерживают обе стороны. Иначе используется DES, прописанный в RFC 2405. Так как размер открытого текста должен быть кратен определенному числу байт, например, размеру блока для блочных алгоритмов, перед шифрованием производится ещё и необходимое дополнение шифруемого сообщения. Зашифрованное сообщение помещается в поле Payload Data. В поле Pad Length помещается длина дополнения. Затем, как и в AH, вычисляется Sequence Number. После чего считается контрольная сумма (ICV). Контрольная сумма, в отличие от протокола AH, где при её вычислении учитываются также и некоторые поля IP-заголовка, в ESP вычисляется только по полям ESP-пакета за вычетом поля ICV. Перед вычислением контрольной суммы оно заполняется нулями. Алгоритм вычисления ICV, как и в протоколе AH, передающий IPsec-модуль узнает из записи об SA, с которым связан обрабатываемый пакет.

Обработка входных IPsec-пакетов

После получения пакета, содержащего сообщение ESP-протокола, приёмный IPsec-модуль ищет соответствующее защищённое виртуальное соединение (SA) в SAD, используя IP-адрес получателя, протокол безопасности (ESP) и индекс SPI. Если соответствующее SA не найдено, пакет уничтожается. Найденное защищённое виртуальное соединение (SA) указывает на то, используется ли услуга по предотвращению повторной передачи пакетов, то есть на необходимость проверки поля Sequence Number. Если услуга используется, то поле проверяется. Для этого, так же как и в AH, используется метод скользящего окна. Приёмный IPsec-модуль формирует окно с шириной W. Левый край окна соответствует минимальному последовательному номеру (Sequence Number) N правильно принятого пакета. Пакет с полем Sequence Number, в котором содержится значение, начиная от N+1 и заканчивая N+W, принимается корректно. Если полученный пакет оказывается по левую границу окна- он уничтожается. Затем, если используется услуга аутентификации, приёмный IPsec-модуль вычисляет ICV по соответствующим полям принятого пакета, используя алгоритм аутентификации, который он узнает из записи об SA, и сравнивает полученный результат со значением ICV, расположенным в поле «Integrity Check Value». Если вычисленное значение ICV совпало с принятым, то пришедший пакет считается действительным. Если проверка дала отрицательный результат, то приёмный пакет уничтожается. Далее производится расшифрование пакета. Приёмный IPsec-модуль узнает из записи об SA, какой алгоритм шифрования используется и секретный ключ. Надо заметить, что проверка контрольной суммы и процедура расшифрования могут проводиться не только последовательно, но и параллельно. В последнем случае процедура проверки контрольной суммы должна закончиться раньше процедуры расшифрования, и если проверка ICV провалилась, процедура расшифрования также должна прекратиться. Это позволяет быстрее выявлять испорченные пакеты, что, в свою очередь, повышает уровень защиты от атак типа «отказ в обслуживании»(DOS-атаки). Далее расшифрованное сообщение в соответствии с полем Next Header передается для дальнейшей обработки.

IKE

IKE (произносится айк, от Internet Key Exchange) — протокол, связывающий все компоненты IPsec в работающее целое. В частности, IKE обеспечивает первоначальную аутентификацию сторон, а также их обмен общими секретными ключами.

Существует возможность вручную установить ключ для сессии (не путать с pre-shared key [PSK] для аутентификации). В этом случае IKE не используется. Однако этот вариант не рекомендуется и используется редко. Традиционно, IKE работает через порт 500 UDP.

Существует IKE и более новая версия протокола: IKEv2. В спецификациях и функционировании этих протоколов есть некоторые различия. IKEv2 устанавливает параметры соединения за одну фазу, состоящую из нескольких шагов. Процесс работы IKE можно разбить на две фазы.

Первая фаза

IKE создает безопасный канал между двумя узлами, называемый IKE security association (IKE SA). Также, в этой фазе два узла согласуют сессионный ключ по алгоритму Диффи-Хеллмана. Первая фаза IKE может проходить в одном из двух режимов:

  • Основной режим
    Состоит из трёх двусторонних обменов между отправителем и получателем:

    1. Во время первого обмена согласуются алгоритмы и хэш-функции, которые будут использоваться для защиты IKE соединения, посредством сопоставления IKE SA каждого узла.
    2. Используя алгоритм Диффи-Хеллмана, стороны обмениваются общим секретным ключом. Также узлы проверяют идентификацию друг друга путём передачи и подтверждения последовательности псевдослучайных чисел.
    3. По зашифрованному IP-адресу проверяется идентичность противоположной стороны. В результате выполнения основного режима создается безопасный канал для последующего ISAKMP — обмена (этот протокол определяет порядок действий для аутентификации соединения узлов, создания и управления SA, генерации ключей, а также уменьшения угроз, таких как DoS-атака или атака повторного воспроизведения).
  • Агрессивный режим
    Этот режим обходится меньшим числом обменов и, соответственно, числом пакетов. В первом сообщении помещается практически вся нужная для установления IKE SA информация: открытый ключ Диффи-Хеллмана, для синхронизации пакетов, подтверждаемое другим участником, идентификатор пакета. Получатель посылает в ответ все, что надо для завершения обмена. Первому узлу требуется только подтвердить соединение.

С точки зрения безопасности агрессивный режим слабее, так как участники начинают обмениваться информацией до установления безопасного канала, поэтому возможен несанкционированный перехват данных. Однако, этот режим быстрее, чем основной. По стандарту IKE любая реализация обязана поддерживать основной режим, а агрессивный режим поддерживать крайне желательно.

Вторая фаза

В фазе два IKE существует только один, быстрый, режим. Быстрый режим выполняется только после создания безопасного канала в ходе первой фазы. Он согласует общую политику IPsec, получает общие секретные ключи для алгоритмов протоколов IPsec (AH или ESP), устанавливает IPsec SA. Использование последовательных номеров обеспечивает защиту от атак повторной передачи.
Также быстрый режим используется для пересмотра текущей IPsec SA и выбора новой, когда время жизни SA истекает. Стандартно быстрый режим проводит обновление общих секретных ключей, используя алгоритм Диффи-Хеллмана из первой фазы.

Как работает IPsec

В работе протоколов IPsec можно выделить пять этапов:

  1. Первый этап начинается с создания на каждом узле, поддерживающим стандарт IPsec, политики безопасности. На этом этапе определяется, какой трафик подлежит шифрованию, какие функции и алгоритмы могут быть использованы.
  2. Второй этап является по сути первой фазой IKE. Её цель — организовать безопасный канал между сторонами для второй фазы IKE. На втором этапе выполняются:
    • Аутентификация и защита идентификационной информации узлов
    • Проверка соответствий политик IKE SA узлов для безопасного обмена ключами
    • Обмен Диффи-Хеллмана, в результате которого у каждого узла будет общий секретный ключ
    • Создание безопасного канала для второй фазы IKE
  3. Третий этап является второй фазой IKE. Его задачей является создание IPsec-туннеля. На третьем этапе выполняются следующие функции:
    • Согласуются параметры IPsec SA по защищаемому IKE SA каналу, созданному в первой фазе IKE
    • Устанавливается IPsec SA
    • Периодически осуществляется пересмотр IPsec SA, чтобы убедиться в её безопасности
    • (Опционально) выполняется дополнительный обмен Диффи-Хеллмана
  4. Рабочий этап. После создания IPsec SA начинается обмен информацией между узлами через IPsec-туннель, используются протоколы и параметры, установленные в SA.
  5. Прекращают действовать текущие IPsec SA. Это происходит при их удалении или при истечении времени жизни (определенное в SA в байтах информации, передаваемой через канал, или в секундах), значение которого содержится в SAD на каждом узле. Если требуется продолжить передачу, запускается фаза два IKE (если требуется, то и первая фаза) и далее создаются новые IPsec SA. Процесс создания новых SA может происходить и до завершения действия текущих, если требуется непрерывная передача данных.

Использование

Протокол IPsec используется, в основном, для организации VPN-туннелей. В этом случае протоколы ESP и AH работают в режиме туннелирования. Кроме того, настраивая политики безопасности определенным образом, протокол можно использовать для создания межсетевого экрана. Смысл межсетевого экрана заключается в том, что он контролирует и фильтрует проходящие через него пакеты в соответствии с заданными правилами. Устанавливается набор правил, и экран просматривает все проходящие через него пакеты. Если передаваемые пакеты попадают под действие этих правил, межсетевой экран обрабатывает их соответствующим образом. Например, он может отклонять определенные пакеты, тем самым прекращая небезопасные соединения. Настроив политику безопасности соответствующим образом, можно, например, запретить веб-трафик. Для этого достаточно запретить отсылку пакетов, в которые вкладываются сообщения протоколов HTTP и HTTPS. IPsec можно применять и для защиты серверов — для этого отбрасываются все пакеты, кроме пакетов, необходимых для корректного выполнения функций сервера. Например, для Web-сервера можно блокировать весь трафик, за исключением соединений через 80-й порт протокола TCP, или через порт TCP 443 в случаях, когда применяется HTTPS. Пример:

IPsec VPN

С помощью IPsec здесь обеспечивается безопасный доступ пользователей к серверу. При использовании протокола ESP, все обращения к серверу и его ответы шифруются. Однако за VPN шлюзом (в домене шифрования) передаются открытые сообщения.
Другие примеры использования IPsec:

  • шифрование трафика между файловым сервером и компьютерами в локальной сети, используя IPsec в транспортном режиме.
  • соединение двух офисов с использованием IPsec в туннельном режиме.

Introduction to IP
Security (IPSec)

This chapter briefly
describes IPSec functionality and associated terminology.


Important

IPSec is a suite
of standard and licensed Cisco features. Contact your Cisco account
representative for detailed information on specific licensing requirements. For
information on installing and verifying licenses, refer to the
System
Administration Guide
.


The following topics
are discussed in this chapter:

Overview

IPSec is a suite
of protocols that interact with one another to provide secure private
communications across IP networks. These protocols allow
the system to establish and maintain secure tunnels with peer security
gateways. IPSec provides confidentiality, data
integrity, access control, and data source authentication
to IP datagrams.

IPSec AH and ESH

Authentication Header (AH) and
Encapsulating Security Payload (ESP) are the two
main wire-level protocols used by IPSec. They
authenticate (AH) and encrypt-plus-authenticate (ESP) the
data flowing over that connection.

  • AH is used to authenticate – but
    not encrypt – IP traffic.Authentication is performed
    by computing a cryptographic hash-based message authentication
    code over nearly all the fields of the IP packet (excluding
    those which might be modified in transit, such as TTL or the
    header checksum), and stores this in a newly-added
    AH header that is sent to the other end. This AH header
    is injected between the original IP header and the payload.

  • ESP provides encryption
    and optional authentication. It includes header and trailer
    fields to support the encryption and optional authentication. Encryption
    for the IP payload is supported in transport mode and for the entire
    packet in the tunnel mode. Authentication applies to the
    ESP header and the encrypted data.

IPSec Transport
and Tunnel Mode

Transport Mode provides
a secure connection between two endpoints as it encapsulates IP
payload, while Tunnel Mode encapsulates the entire IP packet
to provide a virtual «secure hop» between two
gateways.

Tunnel Mode forms the
more familiar VPN functionality, where entire IP packets
are encapsulated inside another and delivered to the destination. It
encapsulates the full IP header as well as the payload.

Security Associations (SAs) and
Child SAs

An Internet Key Exchange-Security
Association (IKE-SA) is used to secure
IKE comicality. SA is identified by two, eight-byte
Security Parameter Indices (SPIs) shared by each
peer during the initial IKE exchange. Both SPIs are carried
in all subsequent messages.

A Child-SA
is created by IKE for use in AH or ESP security. Two Child-SAs
are created as a result of one exchange – Inbound and Outbound. A
Child-SA is identified by a single four-byte SPI, Protocol
and Gateway IP Address and is carried in each AH/ESP packet.

Each SA (IKE
or Child) has an associated lifetime. After the
expiry of lifetime, SAs are deleted. To proactively
establish an SA before the last one expires, SAs are rekeyed
on soft lifetime expiry. Both IKE and Child SAs may be
rekeyed.

Anti-Replay (IKEv2)

Anti-replay
is a sub-protocol of IPSec (RFC 4303) that
is supported for IKEv1 and IKEv2 tunnels. Its main goal
is to prevent hackers injecting or making changes in packets that
travel from a source to a destination. Anti-replay
protocol employs a unidirectional security association to establish
a secure connection between two nodes in the network.

Once a secure connection
is established, the anti-replay protocol uses
a sequence number or a counter. When the source sends a
message, it adds a sequence number to its packet starting
at 0 and increments every time it sends another message. At
the destination end, the protocol receives the message
and keeps a history of the number and shifts it as the new number. If
the next message has a lower number, the destination drops
the packet, and, if the number is larger than
the previous one, it keeps and shifts it as the new number.

The anti-replay
feature may be enabled or disabled via the StarOS CLI. Anti-Replay Window
Sizes of 32, 64, 128, 256, 384
and 512 bits are supported (default = 64 bits).

Behavior for ACL-based
calls differs from Subscriber-based calls.

  • ACL-based. An
    anti-replay configuration change in the CLI will not be
    propagated until a call is cleared and re-established.

  • Subscriber-based. An
    anti-replay configuration change in the CLI will not affect
    established calls but new calls will utilize the new anti-replay configuration.

IPSec
Applications


Important

Support for IPSec
features varies per platform, service type and StarOS release. Refer to the
gateway administration guide and StarOS
Release
Notes
for additional information.


IPSec can be
implemented via StarOS for the following applications:

  • PDN Access: Subscriber IP traffic is routed over an IPSec
    tunnel from the system to a secure gateway on the packet data network (PDN) as
    determined by access control list (ACL) criteria. This application can be
    implemented for both core network service and HA-based systems. The following
    figure shows several IPSec configurations.

Figure 1. IPSec Applications

  • Mobile IP: Mobile IP (MIP) control signals and subscriber
    data is encapsulated in IPSec tunnels that are established between foreign
    agents (FAs) and home agents (HAs) over the Pi interfaces.


    Important

    Once an IPSec
    tunnel is established between an FA and HA for a particular subscriber, all new
    Mobile IP sessions using the same FA and HA are passed over the tunnel
    regardless of whether or not IPSec is supported for the new subscriber
    sessions. Data for existing Mobile IP sessions is unaffected.


  • L2TP: L2TP-encapsulated
    packets are routed from the system to an LNS/secure gateway over an IPSec
    tunnel.

Note that: IPSec can
be implemented for both attribute-based and compulsory tunneling applications
for 3GPP2 services.

IPSec
Terminology

There are several
items related to IPSec support under StarOS that must be understood prior to
beginning configuration. They include:

  • Crypto Access Control List (ACL)
  • Transform Set
  • ISAKMP Policy
  • Crypto Map
  • Crypto Template

Crypto Access Control
List (ACL)

Access Control Lists
define rules, usually permissions, for handling subscriber
data packets that meet certain criteria. Crypto ACLs, however, define
the criteria that must be met in order for a subscriber data packet
to be routed over an IPSec tunnel.

Unlike other ACLs that
are applied to interfaces, contexts, or one or
more subscribers, crypto ACLs are matched with crypto maps. In
addition, crypto ACLs contain only a single rule while
other ACL types can consist of multiple rules.

Prior to routing, the
system examines the properties of each subscriber data packet. If
the packet properties match the criteria specified in the crypto
ACL, the system will initiate the IPSec policy dictated
by the crypto map.

For additional information
refer to the Access Control chapter
of this guide. There you will find a discussion of blacking
and whitelisting, as well as IKE Call Admission Control (CAC).

Transform Set

Transform Sets are
used to define IPSec security associations (SAs). IPSec
SAs specify the IPSec protocols to use to protect packets.

Transform sets are
used during Phase 2 of IPSec establishment. In this phase, the
system and a peer security gateway negotiate one or more transform
sets (IPSec SAs) containing the rules for protecting
packets. This negotiation ensures that both peers can properly
protect and process the packets.

For additional information
refer to the Transform
Set Configuration
chapter of this guide,

ISAKMP Policy

Internet Security Association
Key Management Protocol (ISAKMP) policies are
used to define Internet Key Exchange (IKE) SAs. The
IKE SAs dictate the shared security parameters (such as
which encryption parameters to use, how to authenticate the
remote peer, etc.) between the system
and a peer security gateway.

During Phase 1 of IPSec
establishment, the system and a peer security gateway negotiate IKE
SAs. These SAs are used to protect subsequent communications
between the peers including the IPSec SA negotiation process.

For additional information
refer to the ISAKMP Policy
Configuration
chapter of this guide.

Crypto Map

Crypto Maps define
the tunnel policies that determine how IPSec is implemented for
subscriber data packets.

There are several types
of crypto maps supported by StarOS. They are:

  • Manual crypto maps

  • IKEv2 crypto maps

  • Dynamic crypto maps


Important

The map ip pool command is not
supported within crypto maps on the ASR 5500.


Manual Crypto Maps (IKEv1)

These are static tunnels
that use pre-configured information (including
security keys) for establishment. Because they
rely on statically configured information, once created, the
tunnels never expire; they exist until their configuration
is deleted.

Manual crypto maps
define the peer security gateway to establish a tunnel with, the
security keys to use to establish the tunnel, and the IPSec
SA to be used to protect data sent/received over the tunnel. Additionally, manual
crypto maps are applied to specific system interfaces.


Important

Because manual crypto
map configurations require the use of static security keys (associations), they
are not as secure as crypto maps that rely on dynamically configured
keys. Therefore, it is recommended that they only
be configured and used for testing purposes.


IKEv2 Crypto Maps

These tunnels are similar
to manual crypto maps in that they require some statically configured
information such as the IP address (IPv4 or IPv6) of
a peer security gateway and that they are applied to specific system
interfaces.

However, IKEv2
crypto maps offer greater security because they rely on dynamically generated
security associations through the use of the Internet Key Exchange (IKE) protocol.

When IKEv2 crypto maps
are used, the system uses the pre-shared key configured
for the map as part of the Diffie-Hellman (D-H) exchange
with the peer security gateway to initiate Phase 1 of the establishment
process. Once the exchange is complete, the system
and the security gateway dynamically negotiate IKE SAs to complete
Phase 1. In Phase 2, the two peers dynamically
negotiate the IPSec SAs used to determine how data traversing the
tunnel will be protected.

Dynamic Crypto Maps (IKEv1)

These tunnels are used
for protecting L2TP-encapsulated data between the system
and an LNS/security gateway or Mobile IP data between an
FA service configured on one system and an HA service configured
on another.

The system determines
when to implement IPSec for L2TP-encapsulated data either
through attributes returned upon successful authentication for attribute
based tunneling, or through the configuration of the L2TP
Access Concentrator (LAC) service used for compulsory tunneling.

The system determines
when to implement IPSec for Mobile IP based on RADIUS attribute values
as well as the configurations of the FA and HA service(s).

For additional information, refer
to the Crypto Maps chapter
of this guide

Crypto Template

A Crypto Template configures
an IKEv2 IPSec policy. It includes most of the IPSec parameters
and IKEv2 dynamic parameters for cryptographic and authentication
algorithms. A security gateway service will not function
without a configured crypto template.

Only one crypto template
can be configured per service. However, a single
StarOS instance can run multiple instances of the same service with
each associated with that crypto template.

For additional information, refer
to the Crypto Templates chapter
of this guide.

IKEv1 versus IKEv2

StarOS supports features associated with:

  • IKEv1 as defined in RFC 2407, RFC 2408 and RFC 2409

  • IKEv2 as defined in RFC 4306, RFC 4718 and RFC 5996

The table below compares features supported by IKEv1 and IKEv2.

Table 1. IKEv1 versus IKEv2 Features

IKEv1 IKEv2

IPSec Security Associations (SAs)

Child Security Associations (Child SAs)

Exchange modes:

  • Main mode

  • Aggressive mode

Only one exchange mode is defined. Exchange modes were obsoleted.

Number of exchanged messages required to establish a VPN:

  • Main mode = 9 messages

  • Aggressive mode = 6 messages

Only 4 messages are required to establish a VPN.

Authentication methods:

  • Pre-Shared Key (PSK)

  • Digital Signature (RSA-Sig)

  • Public Key Encryption

  • Revised mode of public Key Encryption

Authentication methods:

  • Pre-Shared Key (PSK)

  • Digital Signature (RSA-Sig)

Traffic Selector:

  • Only a combination of a source IP range, a destination IP range, a source port and a destination port is allowed per IPSec
    SA.

  • Exact agreement of the traffic selection between peers is required.

Traffic Selector:

  • Multiple combinations of of a source IP range, a destination IP range, a source port and a destination port are allowed per
    Child SA. IPv4 and IPv6 addresses can be configured for the same Child SA.

  • Narrowing traffic selectors between peers is allowed.

Lifetime for SAs requires negotiation between peers.

Lifetime for SAs is not negotiated. Each peer can delete SAs by exchanging DELETE payloads.

Multihosting is not supported

Multihosting is supported by using multiple IDs on a single IP address and port pair.

Rekeying is not defined.

Rekeying is defined and supported.

Dead peer Detection (DPD) for SAs is defined as an extension.

DPD is supported by default.

NAT Transversal (NATT) is not supported.

NAT Transversal (NATT) is supported only for subscriber mode.

Remote Access VPN is not defined, but is supported by vendor-specific implementations for Mode config and XAUTH.

Remote Access VPN is supported by default:

  • Extensible Authentication Protocol (EAP)

  • User authentication via EAP is associated with IKE authentication

  • Configuration payload (CP)

Multihoming is not supported.

Multihoming is supported by MOBIKE (IKEv2 Mobility and Multihoming Protocol, RFC 4555)

Mobile Clients are not supported.

Mobile Clients are supported by MOBIKE.

Denial of Service (DoS) protections are not supported.

DoS protections include an anti-replay function.

Supported
Algorithms

IPSec supports the protocols in the
table below, which are specified in RFC 5996.

Table 2. Supported Algorithms

Protocol

Type

Supported Options

Internet Key Exchange version 2

IKEv2 Encryption

DES-CBC, 3DES-CBC, AES-CBC-128, AES-CBC-256

IKEv2 Pseudo Random Function

PRF-HMAC-SHA1, PRF-HMAC-MD5, AES-XCBC-PRF-128

IKEv2 Integrity

HMAC-SHA1-96, HMAC-SHA2-256-128, HMAC-SHA2-384-192.
HMAC-SHA2-512-256, HMAC-MD5-96, AES-XCBC-96

IKEv2 Diffie-Hellman Group

Group 1 (768-bit), Group 2 (1024-bit), Group 5 (1536-bit),
Group 14 (2048-bit)

IP Security

IPSec Encapsulating Security Payload Encryption

NULL, DES-CBC, 3DES-CBC, AES-CBC-128, AES-CBC-256, AES-128-GCM-128, AES-128-GCM-64, AES-128-GCM-96, AES-256-GCM-128, AES-256-GCM-64,
AES-256-GCM-96

Note 

AES-GCM algorithms are supported only on vPC-DI and vPC-SI Platform.

Extended Sequence Number

Value of 0 or off is supported (ESN itself is not supported)

IPSec Integrity

NULL, HMAC-SHA1-96, HMAC-MD5-96, AES-XCBC-96,
HMAC-SHA2-256-128, HMAC-SHA2-384-192, HMAC-SHA2-512-256

Important 

HMAC-SHA2-384-192 and HMAC-SHA2-512-256 are not supported
on vPC-DI and vPC-SI platforms if the hardware doesn’t have crypto hardware.

Boost Crypto
Performance

An

require ipsec-large
command boosts IPSec crypto performance by enabling the resource manager (RM)
task to assign additional IPSec managers to packet processing cards that have
sufficient processing capacity.

configure 
    require ipsec-large 
    end 

This command works with ePDG, PDIF and other StarOS applications.


Important

When IPSec large and demux on MIO are configured together, enable the IPsec large feature (using the require ipsec-large command) before enabling the demux on MIO (using the require demux management-card command).


Refer to the Release Notes accompanying each StarOS build for the latest information on supported products and packet processing cards.

Multiple
Authentication Configuration

List of
authentication methods are defined and associated in Crypto Template. The basic
sample configuration required for OCSP and Certificate based authentication is
as follows. For backward compatibility, the configuration for auth method
inside Crypto Template will be working.

The following are
the configuration considerations:

  • A maximum of three sets of
    authentication methods in the list can be associated.

  • Each set can have only one
    local and one remote authentication method configuration.

  • The existing configuration
    inside the Crypto Template takes precedence over the new auth-method-set
    defined, in case same authentication method is configured at both places.

configure 

CA Certificate for
device certificate authentication:

      ca-certificate name <ca-name> pem url file: <ca certificate path> 

Gateway Certificate:

      ca-certificate name <gateway-name> pem url file: <gateway certificate path> private-key pem url file:<gateway private key path> 
               eap-profile <profile name> 
                     mode authenticator-pass-through 
                     exit  
               ikev2-ikesa auth-method-set <list-name-1> 
                     authentication remote certificate 
                     authentication local certificate 
                     exit  
               ikev2-ikesa auth-method-set <list-name-2> 
                     authentication eap-profile eap1 
                     exit  
               crypto template boston ikev2-subscriber 
                     ikev2-ikesa auth-method-set list <list-name-2> <list-name-2> 
                     ca-certificate list ca-cert-name <ca-name> 
                     exit 

Другие наши интересноые статьи:

  • Что такое ethernet порт роутера
  • Что такое dmz в роутере xiaomi
  • Что такое iptv vlan в роутере
  • Что такое l2tp соединение на роутере huawei
  • Что такое eth на роутере

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии