Объединение сетей с помощью L2TP/IPsec на Mikrotik и Keenetic Ultra II

Появилась задача подключить к локальной сети два дополнительных удалённых офиса. Про настройку OpenVPN сервера для желающим поработать из дома или в командировке я уже рассказывал, однако перспектива выдачи каждому пользователю сети отдельного сертификата с последующей настройкой соединения меня совсем не радовала. Потому для подключения филиалов было решено пойти другим путём.
Объединять сети будем через VPN туннели по технологии L2TP/IPsec без поднятия дополнительных серверов и использования дорогостоящего оборудования, непосредственно на роутерах Mikrotik и Keenetic Ultra II. Поводом для такого объединения, помимо удобства пользователей и моей лени, послужила некорректная работа встроенного L2TP/IPsec клиента в Windows.
Как видно из схемы, пользователи в филиалах должны иметь доступ к терминальному серверу, расположенному за роутером Keenetic Ultra II. Так как на «Кинетике» уже был настроен и благополучно работал L2TP/IPsec сервер, то «Микротикам» досталась роль клиентов. Кроме того, такой вариант существенно проще в настройке, по сравнению с поднятием VPN сервера на «микротике».
Обязательное условие: адреса объединяемых сетей не должны пересекаться между собой.
Настройка L2TP VPN-сервера на роутере Keenetic
С подробностями настройки L2TP/IPsec сервера на Keenetic Ultra можно ознакомиться перейдя по этой ссылке. Там всё просто, потому не буду повторяться. В дополнение к той статье, необходимо остановиться на паре существенных моментов, без которых не возможна нормальная работа VPN туннелей:
- Отключить NAT для клиентов, оно тут будет только мешать;
- Снять галочку, напротив поля «Множественный вход», если она там стояла. Это позволит точно указать IP адрес, выдаваемый клиенту L2TP сервером при подключении;

Для удалённых филиалов я выбрал имена office_01 и оffice_02 и назначил им соответсенно статические адреса 172.16.2.35 и 172.16.2.35. Эти адреса, указываются в качестве шлюзов при создании статических маршрутов для сетей, расположенных за ними. У office_01 внутренняя сеть 192.168.11.0/24, office_02 — 192.168.0.0/24
Настройка Mikrotik в качестве клиента L2TP/IPsec
Настройку удаленного клиента начнём с добавления нового интерфейса L2TP Client в разделе интерфейсов. Указываем IP-адрес L2TP сервера, свои учётные данные и общий ключ шифрования IPSec.

Если вы думаете, что этого достаточно для успешной установки соединения с сервером, поднятом на Keenetic Ultra II, то глубоко заблуждаетесь, ибо настройка «микротов» это всегда боль и страдания. Складывается впечатление, что компания Mikrotik намеренно лишает себя прибыли. Я не понимаю, что мешает выпустить нормальные пошаговые руководства по настройке своих железок и стать ведущим игроком на рынке.
Далее требуется указать нужные алгоритмы шифрования SA (Security Association) в настройках IP->IPsec->Proposals и изменить значение параметра PFS Group с modp1024 на none.
Аббревиатура PFS расшифровывается как Perfect Forward Secrecy — что-то связанное со второй фазой обмена ключами в IPsec. Честно говоря, так глубоко в эту тему не вникал и если не ошибаюсь, то на устройствах от Apple данный параметр в настройках IPsec по умолчанию тоже выключен. В общем, чтобы канал до Keenetic Ultra II поднялся, значение параметра PFS Group должно быть none.

Также скорректируем и профиль шифрования по-умолчанию IP->IPsec->Profiles:

Нажимаем «Применить», и если мы всё сделали правильно, соединение должно быть установлено.
Туннель у нас поднялся. Осталась самая малость, чтобы компьютеры за роутером получили доступ в удалённую сеть 192.168.99.0/24, где находится терминальный сервер. Для этого необходимо добавить правило маскарада и новый статический маршрут.
Переходим во вкладку IP->Firewall->NAT:

На вкладке IP->Routes в качестве шлюза указываем созданный интерфейс l2tpMainOffice, а в поле Pref. Source – наш IP-адрес в виртуальной сети:

Аналогичным образом настраивается и клиент для второй сети.
Напоследок хотелось поделиться несколькими ссылками с сайта центра поддержки KEENETIC (https://help.keenetic.com/hc/ru/):
- VPN-сервер L2TP/IPsec https://help.keenetic.com/hc/ru/articles/360000684919-VPN-сервер-L2TP-IPsec
- Объединение более двух сетей, используя VPN-сервер на Keenetic https://help.keenetic.com/hc/ru/articles/360005620840-Объединение-более-двух-сетей-используя-VPN-сервер-на-Keenetic
- Маршрутизация сетей через VPN https://help.keenetic.com/hc/ru/articles/360001390359-Маршрутизация-сетей-через-VPN
Если считаете статью полезной,
не ленитесь ставить лайки и делиться с друзьями.
Как удалить trojan.carberp.30 (klpclst.dat)
Бесплатный VPN для обхода блокировок в браузере Chrome
Мошенники звонят от лица сотрудников Госуслуг. Чем грозит потеря доступа к вашему аккаунту
Хранение шифрованных данных в облаке Яндекс.Диск средствами Mac OS X Ответ компании DrWeb о троянцах-шифровальщиках семейства Encoder. Возможно ли восстановить файлы. Как снять пароль любого пользователя в Windows
Комментариев: 2
Спасибо тебе добрый человек.
Добрый день. Спасибо за статью, все понятно и полезно. Подскажите пожалуйста, как в данном варианте правильно пробросить порт из белого IP Keenetic за VPN на устройство во внутренней сети MIKROTIK? Пробовал добавлять по стандартной инструкции — не работает.
How to Configure IPsec VPN Between MikroTik Router?-Step by Step.
We have setup MikroTik in different environments, its time for us to build IPsec tunnel between two sites where we have MikroTik routers.
Table of Contents
What is the IPsec tunnel in MikroTik ?
An IPsec tunnel in MikroTik refers to a secure communication channel established between two remote sites or networks using the IPsec (Internet Protocol Security) protocol. With the increasing affordability of internet connectivity, more organisations are utilising the internet to connect their branch offices securely. MikroTik routers provide built-in support for IPsec configuration, making it easy to set up site-to-site VPNs.
IPsec ensures the confidentiality, integrity, and authenticity of data transmitted over the internet by encrypting and authenticating IP packets. By utilising IPsec tunnels, organisations can establish secure connections between their branch sites, enabling them to securely transfer sensitive data and communicate seamlessly.
MikroTik routers offer a user-friendly interface to configure IPsec tunnels, allowing administrators to define IPsec policies, select encryption algorithms, and set up key exchange protocols. The routers authenticate each other using pre-shared keys or digital certificates, establishing a trusted connection. Once the IPsec tunnel is established, all traffic between the sites is encrypted, preventing unauthorised access and ensuring secure communication.
Setting up an IPsec tunnel on MikroTik routers is a cost-effective solution for connecting branch offices securely over the internet. With its built-in IPsec support, MikroTik simplifies the configuration process, making it accessible even to users with limited networking expertise.
Prerequisites:
Before you proceed, you need to have two mikrotik routers both of them are connected with the internet.
Below is the topology that we are going to build.
As you can see, I have two locations: the headquarters and a branch site that we’re planning to deploy.
The headquarters (HQ) has a local network with the IP range of 10.1.1.0/24, while the branch site has the IP range of 10.2.2.0/24.
Currently, both locations have internet connectivity, but they are unable to communicate with each other. Let’s verify this situation.

Test the connectivity between MikroTik sites.
Before we proceed with the configuration, let’s first test the connectivity from the site to the remote branch and the internet.
I’ve logged into the HQ machine and I’m currently checking if I can access the internet. It appears that the internet connection is functioning smoothly, as you can see.

Let me now ping the remote PC with the address 10.2.2.50. As you can see, the ping has failed. However, once we establish the Ipsec site-to-site tunnel between these two locations, you will be able to communicate with each other.
And that’s out end goal.

Step by Step guide to configure IPsec site to site VPN between two MikroTik routers.
Let’s begin by configuring IPsec in the MikroTik router at the headquarters before moving on to the next steps.
Configure Headquarters.
To get started, log in to the Winbox utility and access the HQ router. Once you’re logged in, click on IP -> IPsec.

A new window will open, where we will configure the IPsec settings.
When it comes to IPsec, it consists of two phases: phase 1 and phase 2. Let’s begin by configuring phase 1, and then we can move on to phase 2.
MikroTik Phase1 configuration.
Configure IPsec profile.
Setting up the IPsec profile is the first step in the configuration process.
In the IPsec profile tab, click on the plus icon to create a new profile.

A new window now pop up, where you need to define the profile parameters.
A new window will appear, where you can define the profile parameters.
Fill in the following details:
- Name: Give a name to the profile, such as “Branch-01-profile”.
- Hash Algorithm: Set it to “sha256”.
- Encryption Algorithm: Choose “aes-256”.
- DH Group: Select “modp 1536”.
- NAT Traversal: I am unchecking this option since this MikroTik device is not behind any NAT device. It has direct access to the public internet, and the public IP is configured on the WAN interface.
Once you have entered all the necessary information, click “Ok” to proceed.

Configure the Peer information.
You can now navigate to the “Peers” tab and click on the plus icon to add a new peer.
Name: Provide a descriptive name for the peer, which will help identify the associated site for this tunnel. For example, you can use “branch-01-peer” as the name.
Address: Enter the public IP address of the remote peer, which corresponds to the public IP address of branch1.
Profile: Select the phase 1 profile that we have recently defined.
Exchange mode: Set the exchange mode to IKE2, which refers to ISAKMP version 2. It is important to ensure that both ends have the same exchange mode.
Make sure that the “Passive” option is unchecked, and enable the “Send Initial_contact” option.
Note: Enabling the “Passive” option means that this particular site will not initiate the IPSec connectivity. Depending on your requirements, you can choose the appropriate configuration.
Click on the “Ok” button to save the changes.

Configure the Pre-shared key.
We’ve already defined our peers. For these peers to authenticate effectively, it’s necessary to set a pre-shared key that’s identical at both ends.
So, go ahead and specify the pre-shared key, and don’t forget to note it down.
Now, navigate to the ‘Identities’ tab, and click on the plus icon to add a new identity.
Peer: Select the peer that we previously defined.
Authentication Method: Choose ‘pre-shared key’
Secret: Input a complex pre-shared key and remember to note it down for future reference.

Configure the phase2 configuration.
We’ve successfully completed Phase 1 of the tunnel configuration. It’s time to progress to Phase 2 configuration.
Configure IPsec proposal.
Phase 2 starts off with the IPsec proposal. To get started, locate the proposals tab, and click on the plus icon to create a new proposal.
Setting up the IPsec proposal:
A new window should pop up on your screen.
Name: Here, you’re required to input the name of the proposal.
Authentication Algorithms: input ‘sha256’
Encryption Algorithm: Enter ‘aes 256 cbc’
PFS Group: Key in ‘modp1536’
Once these fields are filled, click ‘OK’ to finalize the settings.

Configure the policies.
We need to specify the traffic that will be sent through the tunnel with encryption enabled.
Having examined the topology, our headquarters’ traffic is on the 10.1.1.0/24 network, while the remote branch operates on the 10.2.2.0/24 subnet.
Our goal is to encrypt this traffic through the tunnel.
You need to navigate to the policies tab and click on the plus icon.
General settings: –
Peer: Choose the peer that we’ve previously configured from the drop-down menu. – Tunnel: Please make sure to check this box.
Source Address: For this, we are using 10.1.1.0/24.
Destination Address: Here, we are using 10.2.2.0/24.
Now, move over to the actions tab.

In the “Actions” tab,
Action: “Encrypt.”
Proposal: Select the encryption we defined.
Retain the default settings for everything else and click “OK.”

Configure the firewall NAT policy for IPsec.
We’ve successfully configured the IPsec tunnel, and now we’re proceeding to set up the NAT policy to exclusively accept the traffic that’s to be sent through the tunnel.
First, navigate to IP: Firewalls -> NAT.
Here, click on the plus icon to initiate the creation of a new NAT policy.
When the NAT configuration window appears, please input the following under the ‘General’ section:
Chain: srcnat
Src. Address: 10.1.1.0/24
Dst. Address: 10.2.2.0/24

Action: Select “Accept” from the “Actions” dropdown menu.
Next, make sure to check the log box before clicking “Ok”.

You’ll find the newly created policy at the bottom of the NAT. move the NAT policy to the top.
To move the NAT policy to the top drag the newly created policy and move it to the top.

Configure the Branch site.
Just as we configured the headquarters router, we are now moving forward to configure the branch side.
The steps we’ll follow will mirror those we took previously, though the specific values will be just the opposite.
Configure the IPsec profile.
First, log into the branch side using the Winbox GUI.
Next, we’ll configure the MikroTik IPsec profile.
Navigate to -> IP -> IPsec -> Profiles
Once you’re there, click on the plus icon to add the profile.
Name, type in ‘hq-profile1’.
Hash Algorithm, select ‘Sha256’.
Encryption Algorithm, choose ‘aes256’.
DH Group, pick ‘modp1536’.
Uncheck the box for NAT traversal. Since the router is directly connected to the internet and not behind the NAT device, this isn’t necessary.
To finish up, click ‘Ok’.

Configure the Peers.
You can now go ahead and click on the ‘Peers’ tab, followed by clicking on the plus icon to add a new peer.
Name: hq-peer1
Address: input the public IP address of the HQ office.
Profile: Select the profile we recently created.
Exchange Mode: IKE2.
Check the box labeled ‘Send INITIAL_CONTACT’.

Configure pre-shared key.
Click on the ‘Identities’ tab and then on the plus icon to add a new identity.
Peer: Here, you’ll need to select the appropriate peer.
Authentication Method: Choose ‘pre-shared-key’.
Secret: Copy and paste the same pre-shared key that you previously used on the headquarters (HQ) remote side.

And click on Ok.
Configure Proposals
In the Proposals tab, click on the plus icon to add new proposals.
Name: HQ Proposal
Auth Algorithms: SHA-256
Encr. Algorithms: AES-256 CBC
PFS Group: MODP1536

Configure IPsec policy.
In the IPsec policise tab, click on the plus icon to add new policy.
General:
Peer: Choose the peer from the drop down.
Check the box that says Tunnel.
Src.Address: 10.2.2.0/24
Dst.Address: 10.1.1.0/24
Click on Action tab.

In the action drop down choose encrypt.
Proposal : choose the proposal that we defined and click on Ok.

Configure the NAT policy.
Goto IP-> Firewall -> NAT
Click on the plus icon to add new NAT rule.
Chain: srcnat
Src Address: 10.2.2.0/24
Dst Address: 10.1.1.0/24

Click on the Action tab.
Action: Choose accept from the drop down and you may also check the log option.
And click on Ok.

Like we did before, move the NAT policy to the top.

Test the MikroTik IPsec connectivity.
Having completed the configuration, let’s now proceed with the testing of Phase 1.
Please navigate to: IP -> IPsec -> Active Peers
If everything has been correctly done up to this point, you should see that the IPsec peering has been successfully established in Phase 1.
As you could see, both the headquarters and branches have IPsec tunnels where Phase 1 has been established.
HQ IPsec status.

Branch IPsec status.

Check the Connectivity from Each Side
Let’s now log into the HQ machine and attempt to ping the branch machine.
As you can see, we captured the first ping before the IPSec deployment, which was failed,. After deploying IPSec, we ran another ping test. And it is successful.

Let me initiate ping from the other side as well.
As you can see, the other side also worked just fine.

And that is how you can setup an IPsec site to site VPN tunnel using mikrotik router, and it is very easy to configure as well.
MiViLiSNet
MikroTik, virtualisation, Linux, servers, networks and more
Mikrotik IPSec services
This is the first article in a series about IPSec services on Mikrotik platform. We will discuss a basic theory of IPSec services. On that foundation, we will explore a few common scenarios for implementation.
I will demonstrate each scenario in the virtual environment and provide you with detailed explanation. In addition, I will publish the basic configuration scripts that you can use in your laboratory.
The MikroTik IPSec series will cover many hot topics. The original series consists of:
- What is IPSec? (this article)
- My virtual lab layout – original version 2 (2016) and updated version 5 (2020)
- Basic troubleshooting techniques
I will also present to you my virtual lab. That part will help you to understand the scenarios and to build your own testing environment. All scenarios will be presented in the same environment.
This part is more theoretical. This is the essence of the theory. You need to understand it well and to build a good foundation for further work.
Before we begin, I need to write a word of caution. In case that VPN or encryption technologies are considered forbidden and/or illegal in your country, please stop further reading and leave this page. You have been warned!
What is IPSec?
IPSec is a suite of the services intended to protect the data exchange over the unsecured IPv4 or IPv6 networks.
In IT jargon, when we speaking about IPSec, we mean IPSec VPN tunnel. In addition, the IPSec protocol is short for the IPSec protocol suite. I will use this convention through the series.
IPSec tunnel is dynamic non-routable VPN tunnel. That means that we have to establish it when we need exchange of data and we cannot assign an IP address to it. Without the IP address, this kind of tunnel cannot be used as part of the routing table.
IPSec protocol is widely used in today’s corporate networks and it’s considered the de facto standard for secure communication over public networks.
IPSec suite includes the following protocols:
- Authenticated Header (AH)
- Encapsulation Security Payload (ESP)
- Internet Key Exchange (IKE)
We can use only AH, only ESP or both AH and ESP protocols in our implementations. IKE protocol is always used.
IPSec protocols are very sensitive to time synchronization. For best experience, it is recommended that both sides use a NTP service.
IPSec tunnel can be used in two modes:
- Transport
- Tunnel
In the transport mode, IPSec tunnel is used to protect the direct communication between two hosts inside the same network. For example, we can protect the communication between user’s laptop and the database server or between the application and database server.
![]()
In the tunnel mode, we want to protect only part of the communication path between two hosts. The hosts are separated with the gateways (routers), that will route the whole network traffic over the Internet.
![]()
Both gateways will act as the termination points for the IPSec VPN tunnel. Only that part of the interconnection path between our hosts is encrypted.
One host will send the IP packet. That packet will travel as unencrypted inside the local network. On the gateway, packet will be collected and, according to the specific rules, it will be encrypted and sent over the Internet to the other gateway.
The second router will receive this encrypted packet, inspect it and, if it match the appropriate rules, decrypt it and send to the destination host. Then the destination host will send the answering packet back using same mechanism.
More details about IPSec protocols
We need to understand IPSec protocols, if we want to master it. We will not going through the whole theory of IPSec here.
Authentication Header
Authentic Header or AH protocol is designed only to protect the authentication of the packet content. It will not encrypt the data and therefore it will not protect it from eavesdropping.
Whoever see the packet can also read the contents. However, the contents cannot be altered by third party.
AH protocol will create its own packet header. The value of the header depends on the packet content.
Position of the header depends on the connection mode. In the transport mode, the header is calculated and inserted after the original IP header.
In the tunnel mode, gateway will create completely new IP packet with the secured header and the payload of that packet will be the original IP packet.
For authentication between the parties, we can use either MD5 or SHA1 protocol. The SHA1 protocol is recommended.
AH protocol is described in details inside the RFC 4302.
Encapsulation Security Payload (ESP)
Encapsulation Security Payload or ESP protocol is designed for the data protection. This protocol will encrypt the data part of the packet (or the payload) and hide it from third parties. The packet header is not encrypted and it’s still visible over the Internet.
ESP protocol uses its own identification protocols. Therefore, we do not need to use AH. In addition, using AH in conjunction with ESP protocol will result in the increased security of the tunnel.
For the data encryption, this tunnel will use one of the well-known encryption algorithms, like:
- DES
- 3DES
- AES 128/192/256 bits
- Blowfish
- Camellia 128/192/256 bits
- Twofish
It’s recommended that you use at least AES algorithm, as DES and 3DES are weak.
The ESP header have three part:
- ESP Header
- ESP Trailer
- ESP Authentication Data
Again, depending on the traffic mode, position of the headers will vary. In the tunnel mode, the complete original packet is used as payload. This will encrypt it and protect it during the transport.
In the transport mode, the ESP header is inserted behind original IP header and then the IP Trailer. Original content is encrypted and attached next, as payload. Behind it will be ESP Authentication Data. Original IP header is not touched or altered in this mode.
ESP protocol is described in details inside the RFC 4303.
A few advanced models of Mikrotik Routerboards have hardware acceleration for ESP protocol:
- RB 1000
- RB 1100AHx2
- All Cloud Core Router (CCR) devices
- RB 850Gx2
The CPU on those models is optimized for the faster processing of the AES-CBC and SHA1/SHA256 algorithms. All other calculations are performed in the software mode.
Internet Key Exchange protocol
Internet Key Exchange or IKE protocol is the most often used protocol for the key exchange over the Internet.
This service (or daemon) works only during the certain periods of establishing IPSec tunnels. The main goals of IKE protocol are to:
- perform the exchange of crypto keys in the secure way over the Internet
- provide mutual authentication of both parties
- calculate and manage the Security Associations (SA) values
The SA values are most important for every tunnel. If values of the SA are not compatible on both sides, tunnel cannot be established.
IPSec phases
The establishment of IPSec tunnel has two phases:
- IKE phase I
- IKE phase II
IKE phase I
IKE phase I will occur when two devices (most often routers) identify the first packet that needs to be send through encrypted tunnel. In that moment, the IKE daemon will run and initiate the connection process.
In this phase, we need to define the peer with which we need to establish the tunnel. Both sides must have the proper definition of the matching peer on the other side of the tunnel.
If this definition is not correct, the tunnel cannot be initialized. This is one of the common mistakes during the configuration of IPSec tunnels.
We need to harmonize following parameters in this phase:
- The IP address of the matching peer
- An authentication algorithm (MD5, SHA-1,…)
- An encryption algorithm (3DES, AES,…)
- A lifetime of the tunnel (like 1 day or 5 GB of data)
- A Diffie-Helman (DH) group (at least DH group 2 – 1024 bits)
- Are we passing through the NAT (NAT-T option)
- Should we send initial contact?
- Dead Peer Discovery (DPD) settings
DPD is a mechanism that router will use to determinate if other side is still “alive”. Every side will send the R-U-There message every 30 seconds. If N messages during the period of T seconds are not answered, router will conclude that other side is not alive anymore. In addition, router will destroy tunnel and its SA identifications.
The Diffie-Helman algorithm is designed with goal that two parties can build common crypto key over the Internet. Moreover, neither side have the complete key in the beginning. Key will be generated dynamically every time when tunnel is build.
This key will be used for further encryption of other traffic. It’s recommended to use the key with length of at least 1024 bits or DH group 2. However, stronger key is advised.
DH algorithms are described in details inside the RFC 2409 and RFC 3526.
IKE phase II
The second phase in the IPSec establishment will be used to encrypt the packets between endpoints (hosts). It covers:
- Rules for the data protection (proposal)
- Rules for the communication (policies)
Inside proposal, we must specify identical authentication and encryption algorithms, lifetime and Perfect Forward Security parameter. We should use at least the SHA-1 authentication protocol and AES-128-CBC bit encryption protocol.
The parameter of the lifetime will keep the tunnel alive for the specific predefined period. After the time elapsed, tunnel will be either refreshed with the new key or destroyed. The usual lifetime period is 8 hours, but you can shorten it for sensitive applications. However, too short period will require that routers spending their precious CPU time to recalculate the keys more often.
Perfect Forward Security or PFS is mechanism that uses same DH algorithm as IKE phase I to calculate keys for every tunnel established between two hosts.
Usage of the PFS is optional. We can omit it. However, it’s good practice to use the PFS. In addition, same rule about the key length should be applied here – at least the DH group 2 or 1024 bits.
The tunnel life
As we said in the beginning, IPSec tunnel is dynamic. Therefore, it is established when we need it and it is destroyed when we do not need it any more. Moreover, every IPSec tunnel had the lifetime.
Every new tunnel will use new crypto key. That crypto key will be generated dynamically. Therefore, if the key is compromised at one time, only portion of the traffic can be decrypted.
We can limit the life of the tunnel in two ways, either a period of time or an amount of data that can be exchanged. The second method will be used either when we working in sensitive environment or exchanging a large amount of data.
Every tunnel will use two counters – a soft and hard counter. The soft counter is used to determinate a moment when we need to renew the tunnel. In case that communication is disturbed and that tunnel is not active in that moment, our device will wait the predefined time until the hard counter is reached. That is the signal that tunnel should be destroyed.
License requirements
There is no special requirements for IPSec services on any license level.
For full details related to Mikrotik RouterOS license level, please visit this page.
Where is IPSec located?
IPSec service can be found in the menu IP > IPSec or through command ip ipsec on the console.
![]()
IPSec packet is installed on every Mikrotik Routerboard device. For the software x86 routers, this packet is optional. There are two packets related to the VPNs in the x86 RouterOS:
- Security – this one is for IPSec service
- PPP – this one covers PPP services, including PPTP and L2TP VPN services
You need one paper
When we summarize this very long post, we can see that we need to harmonize many settings between two parties. It is wise to produce one document (it can be even plain text file) where we will record all parameters and exchange it with other party. On that way, we can shorten the time needed for implementation.
![]()
As you can see from this sample, we will enlist all parameters. The pre-shared key should not be exchanged in this document, rather over the SMS or any other communication channel. In this demo, we will use the key Test1234.
I saw too many failed implementations just because both sides were lazy to write parameters on the paper. In addition, when you harmonize the parameters, you can re-check settings again very easy if any problem occur. Moreover, you can than push other side to do so, having this paper as good argument.
That’s all about the essential theory of IPSec tunnels. This basis will help us to build our lab and then to bravely go in the world of IPSec tunnels. Stay tuned.
Blog of Khlebalin Dmitriy
Cisco-Mikrotik IP-IP. Туннель с Микротиком с белым IP.
Наконец дошли руки посмотреть интеграцию с Cisco. GRE_ipsec за NAT так и не заработал, решили посмотреть схему IP_ipsec (IP-IP).
До сего момента я никогда ранее не пробовал строить такие туннели, наткнулся вот на этот пост и решил попробовать:
Спасибо автору, за понятный, а главное, рабочий вариант.
Набросал вот такую схему в GNS3.
Сначала попробую настроить туннель с Микротиком с белым IP, затем с Микротиком за NAT.

Настроим Cisco.
Cisco_head(config-if)#ip address 77.77.77.226 255.255.255.0
*Mar 1 00:12:08.019: %LINK-3-UPDOWN: Interface FastEthernet0/0, changed state to up
*Mar 1 00:12:09.019: %LINEPROTO-5-UPDOWN: Line protocol on Interface FastEthernet0/0, changed state to up
Enter configuration commands, one per line. End with CNTL/Z.
Cisco_head(config)#interface fastEthernet 0/1
Cisco_head(config-if)#ip address 10.192.0.1 255.255.252.0
*Mar 1 00:16:26.039: %LINK-3-UPDOWN: Interface FastEthernet0/1, changed state to up
*Mar 1 00:16:27.039: %LINEPROTO-5-UPDOWN: Line protocol on Interface FastEthernet0/1, changed state to up
*Mar 1 00:16:32.151: %SYS-5-CONFIG_I: Configured from console by console

Пропишем статический маршрут в нашу сеть филиала:
Cisco_head(config)#ip route 88.88.88.0 255.255.255.0 fastEthernet 0/0
Добавим в конфиг:
! Политика авторизации — хеш мд5 и шифрование 3des по парольному ключу (pre-share)
crypto isakmp policy 20
encr 3des
hash md5
authentication pre-share
! group2 означает, что в микротике надо установить dh-group=modp1024
group 2
crypto isakmp key MyPassWord address 88.88.88.2 no-xauth
crypto isakmp keepalive 30
! Трансформ. Внимание! Используется transport, а не tunnel режим
crypto ipsec transform—set transform-2 esp-3des esp—md5-hmac
mode transport
crypto dynamic-map dynmap 10
set transform-set transform-2
reverse-route
crypto map vpnmap client configuration address respond
crypto map vpnmap 5 ipsec-isakmp dynamic dynmap
crypto map vpnmap 10 ipsec-isakmp
crypto map vpnmap 93 ipsec—isakmp
description Mikrotik_Local
set peer 88.88.88.2
set security-association lifetime seconds 86400
set transform-set transform-2
! pfs group2 означает, что в микротике надо установить dh-group=modp1024
set pfs group2
! access-лист, разрешающий соединение
match address 137
! Сам тоннель (здесь указываем наш внешний интерфейс)
interface Tunnel93
description tunnel_Mikrotik
ip unnumbered FastEthernet0/0
tunnel source 77.77.77.226
tunnel destination 88.88.88.2
! тип тонеля ipip
tunnel mode ipip
interface FastEthernet0/0
description Internet
ip address 77.77.77.226 255.255.255.224
no ip redirects
no ip unreachables
no ip proxy-arp
ip wccp web-cache redirect out
ip virtual-reassembly
ip route-cache policy
no ip mroute-cache
duplex auto
speed auto
no mop enabled
! ВКЛЮЧАЕМ ШИФРОВАНИЕ НА ИНТЕРФЕЙСЕ
crypto map vpnmap
! Роутинг сети, находящейся за микротиком
ip route 192.168.88.0 255.255.255.0 Tunnel93
! Разрешение на соединение тоннеля
access-list 137 permit ip host 77.77.77.226 host 88.88.88.2
Enter configuration commands, one per line. End with CNTL/Z.
% Interface Tunnel93 does not support adjustable maximum datagram size
*Mar 1 02:12:54.603: %SYS-5-CONFIG_I: Configured from console by console
Зададим IP на туннельном интерфейсе:
Enter configuration commands, one per line. End with CNTL/Z.
Cisco_head(config-if)#ip address 10.33.0.1 255.255.255.0
*Mar 1 02:27:29.947: %SYS-5-CONFIG_I: Configured from console by console
! Роутинг сети, находящейся за микротиком сразу поправим на IP нашего туннельного интерфейса.
no ip route 192.168.88.0 255.255.255.0 Tunnel93
ip route 192.168.88.0 255.255.255.0 10.33.0.1
Со стороны Микрота (бранч).


Здесь же сразу пропишем руками статический маршрут в Головной офис:

Интерфейсы-IP Tunnel. Добавить:

На циске MTU выставили 1460, здесь соответственно выставляем тоже самое.
В разделе IP-IPSec-Proposals в дефолтном правиле ОБЯЗАТЕЛЬНО сменить SHA1 на MD5!

IP-IPSec-Peers. Добавить:

В Profiles правим:

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

Если это так, то должна подняться сессия:

И автоматически сгенерируются политики:

IP-Routes. Добавим:

Для более детального логирования добавим:

После этого можно заглянуть обратно в IP-IPSec, закладка Instaled SAs, и вы должны увидеть, что байты бегут по туннелю в обе стороны:

В итоге, у нас со стороны микрота получились следующие маршруты:

Проверим MTU со стороны Микрота (запингуем внутреннюю сетку головы большими пакетами):


Пакеты пролазят-это радует.
Для верности посмотрим, что у нас от компа до компа:


В целом все так, как должно быть.
На этом настройка закончена, но самое интересное, сделать все тоже самое за NAT.
Но это уже тема следующего повествования…
Всем хорошей работы.
P.S. В продакшине оказалось не все так гладко, как на стенде. В Голове у нас стоят маршрутизаторы Cisco ISR 4331, туннель никак не хотел «подниматься», оказалось все дело в прошивке, пришлось их обновлять до последних прошивок. Все сложилось не так гладко, как хотелось бы, но сложилось. Еще раз благодарю Рому и Стаса за подробные разъяснения по некоторым, непонятным для меня вопросам (а их было не мало), по теме. В настоящий момент в продакшин введено уже два Микрота пока с белыми адресами. Две недели, полет нормальный… Будем посмотреть, как события будут развиваться дальше….
Share this:
Понравилось это:
Sorry, the comment form is closed at this time.
О сайте
Записки из мира IT…
В этом блоге, я пишу заметки о своей, как повседневной жизни, так и жизни и работе в сфере IT технологий. Собираю интересные ссылки, выражаю свои мысли и прочее… В основном посты посвящены, Управленческим моментам и решениям, различным продуктам Microsoft и VMWare, которые я эксплуатирую многие годы, Nix, MacOS, сетке, и другим интересным вопросам и задачам, с которыми приходится ежедневно сталкиваться и иметь дело. Здесь приведены не только мои посты, но и посты, которые были найдены мною на безграничных просторах интернета. Все написанное здесь, было проделано мною или моими коллегами при моем непосредственном участии на виртуальных машинах или в продакшин среде, о чем свидетельствуют комментарии в текстах. Всем удачи в работе.