- Openswan L2TP/IPsec VPN client setup
- Contents
- Installation
- Configuration
- NetworkManager
- OpenSwan
- Running Openswan in a container
- xl2tpd
- Routing
- Routing traffic to a single IP address or subnet through the tunnel
- Routing all traffic through the tunnel
- Troubleshooting
- Tips and tricks
- Script start up and shut down
- A further script
- Script to resolve dns names and connect
- L2TP/IPSEC между роутером MikroTik и Ubuntu Linux
- 1. L2TP сервер на стороне MikroTik
- 2. L2TP клиент Ubuntu Linux
- 3. MikroTik IPSEC
- 4. Ubuntu IPSEC
- Вам также может понравиться
- Мониторинг состояния tcp-соединений в Nagios/Icinga
- Ускоряем Graphite-web
- OpenSSH и эллиптическая криптография (ECC)
- Устанавливаем Puppet Dashboard
- 5 комментариев “ L2TP/IPSEC между роутером MikroTik и Ubuntu Linux ”
Openswan L2TP/IPsec VPN client setup
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
This article describes how to configure and use a L2TP/IPsec Virtual Private Network client on Arch Linux. It covers the installation and setup of several needed software packages. L2TP refers to the w:Layer 2 Tunneling Protocol and for w:IPsec, the Openswan implementation is employed.
This guide is primarily targeted for clients connecting to a Windows Server machine, as it uses some settings that are specific to the Microsoft implementation of L2TP/IPsec. However, it is adaptable with any other common L2TP/IPsec setup. The Openswan wiki features instructions to set up a corresponding L2TP/IPSec Linux server.
Contents
Installation
To use with NetworkManager, install the networkmanager-l2tp and strongswan packages.
Now you can start openswan.service . If it’s not running you may get an error message about a missing pluto_ctl connect(pluto_ctl) failed: No such file or directory .
Run ipsec verify to check your configuration and resolve possible issues before continuing.
Configuration
NetworkManager
Open the NetworkManager UI, then:
- Go to Network > VPN. Click «+»
- Select «Layer 2 Tunneling Protocol (L2TP).»
- You can choose a name for the VPN.
- Enter Your VPN Server IP for the Gateway.
- Enter Your VPN Username for the User name.
- Right-click the ? in the Password field, select Store the password only for this user. (If this option gives you trouble, you might want to use «Store password for all users»)
- Enter Your VPN Password for the Password.
- Leave the NT Domain field blank.
- Click the IPsec Settings. button.
- Check the Enable IPsec tunnel to L2TP host checkbox.
- Leave the Gateway ID field blank.
- Enter Your VPN IPsec PSK for the Pre-shared key.
- OK, then click Add to save the VPN connection information.
Now you should be able to start the VPN, by switching the Toggle-Button on.
OpenSwan
Edit /etc/ipsec.conf to contain the following lines:
This file contains the basic information to establish a secure IPsec tunnel to the VPN server. It enables NAT Traversal for if your machine is behind a NAT’ing router (most people are), and various other options that are necessary to connect correctly to the remote IPsec server. The next file contains your pre-shared key (PSK) for the server.
Create the file /etc/ipsec.secrets : It should contain the following line:
Remember to replace the local ( 192.168.0.123 ) and remote ( 68.68.32.79 ) IP addresses with the correct numbers for your location. The pre-shared key will be supplied by the VPN provider and will need to be placed in this file in cleartext form. You may find this file already exists and already have some data, try to back it up and create a new file only with your PSK if you will see «Can’t authenticate: no preshared key found for . » when enabling connection in next section. Do not forget to set proper permissions (600) for this file or you will get error message «We cannot identify ourselves with either end of this connection.».
Add the connection, so it’s available to use:
At this point the IPsec configuration is complete and we can move on to the L2TP configuration.
Running Openswan in a container
Do not forget to add CAP_SYS_MODULE capability and access to host module tree. Example for nspawn:
xl2tpd
Edit /etc/xl2tpd/xl2tpd.conf so it has the following contents:
This file configures xl2tpd with the connection name, server IP address (which again, please remember to change to your servers address) and various options that will be passed to pppd once the tunnel is set up.
Now create /etc/ppp/options.l2tpd.client with the following contents:
Place your assigned username and password for the VPN server in this file. A lot of these options are for interoperability with Windows Server L2TP servers. If your VPN server uses PAP authentication, replace require-mschap-v2 with require-pap .
This concludes the configuration of the applicable software suites to connect to a L2TP/IPsec server. To start the connection do the following:
At this point the tunnel is up and you should be able to see the interface for it if you type:
You should see a pppX device that represents the tunnel. Right now, nothing is going to get routed through it. You need to add some routing rules to make it work right:
Routing
Routing traffic to a single IP address or subnet through the tunnel
This is as easy as adding a routing rule to your kernel table:
Note xxx.xxx.xxx.xxx is the specific ip address (e.g. 192.168.3.10) or subnet (e.g. 192.168.3.0/24) that you wish to communicate with through the tunnel device (e.g. ppp0).
Note yyy.yyy.yyy.yyy is «peer ip» of your pppX device used to route traffic to tunnel destination xxx.xxx.xxx.xxx.
See example below for command to identify tunnel device name and peer ip and then add route. :
Routing all traffic through the tunnel
This is a lot more complex, but all your traffic will travel through the tunnel. Start by adding a special route for the actual VPN server through your current gateway:
This will ensure that once the default gateway is changed to the ppp interface that your network stack can still find the VPN server by routing around the tunnel. If you miss this step you will lose connectivity to the Internet and the tunnel will collapse. Now add a default route that routes to the PPP remote end:
The remote PPP end can be discovered by following the step in the previous section. Now to ensure that ALL traffic is routing through the tunnel, delete the original default route:
To restore your system to the previous state, you can reboot or reverse all of the above steps.
The route creation can also be automated by placing a script in /etc/ppp/ip-up.d.
Troubleshooting
Issue: journalctl logs VPN connection: failed to connect: ‘Could not restart the ipsec service.
Solution Make sure you have strongswan installed
Issue: I get a message from pppd saying «Failed to authenticate ourselves to peer» and I have verified my password is correct. What could be wrong?
Solution 1: If you see the following in your /var/log/daemon.log:
then you are authenticating against a SonicWALL LNS that does not know how to handle CHAP-style authentication correctly.
The solution to this is to add the following to your options.l2tp.client file:
This will cause the SonicWALL to default to the next authentication mechanism, namely MSCHAP-v2. This should authenticate successfully, and from this point xl2tpd should successfully construct a tunnel between you and the remote L2TP server.
Solution 2: If you see the following in your journal after running journalctl -ru xl2tpd as root:
Try adding domain name in front of username in your options.l2tpd.client file (note the double backslash), i.e:
Tips and tricks
Script start up and shut down
You can create some scripts either in your home directory or elsewhere(remember where you put them) to bring up the tunnel then shut it back down.
First, a utility script to automatically discover PPP distant ends:
Next, the script to bring the tunnel up. This will replace the default route, so all traffic will pass via the tunnel:
Finally, the shutdown script, it simply reverses the process:
A further script
Above script really help me work. And notice the script use fixed ip, and someone like me may change net vpn addr, i would like to put my further script below(not sure how to add attachment, so just raw ):
Script to resolve dns names and connect
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
Very useful if you have dynamic IP for the server.
Источник
L2TP/IPSEC между роутером MikroTik и Ubuntu Linux
Появилась потребность в организации VPN тунеля между локальным роутером MikroTik c RouterOS на борту и удаленным сервером на базе Ubuntu Linux. Причем сервер должен выглядеть для локальной сети местным, т.е. находится в этом же L2-сегменте. В качетве тунеля был выбран l2tp, практика показывает что он более стабилен, чем тот же pptp. Так как l2tp не обеспечивает шифрование данных поверх него был настроеен ipsec. В качестве сервера l2tp выступает RouterOS. Конфигурация узлов следуюущая:
Узел | Внешний адрес | Локальный адрес |
MikroTik | 192.168.0.1 | 10.0.0.1/24 |
Linux | 192.168.1.100 | 10.0.0.100 |
1. L2TP сервер на стороне MikroTik
Создаем пользоваьеля для VPN.
Для того чтобы присутсвие удаленного сервера в локальной сети работало необходимо Proxy ARP на локальном интерфесе.
2. L2TP клиент Ubuntu Linux
Устананвливаем xl2tpd, это сервер и клиент для протокола l2tp.
Приводим конфигурационный файл /etc/xl2tpd/xl2tpd.conf к следующему виду
Добавляем учетные данные пользователя в /etc/ppp/chap-secrets
Тунель долежен подняться и работать. Однако, данные передаются через интернет инкапсулированными без шифрования, в большинстве случаем это не приемлемо. Поэтому продолжаем и настраиваем ipsec поверх l2tp-тунеля.
3. MikroTik IPSEC
Политики шифрования трафика.
4. Ubuntu IPSEC
В Linux нам потребуется два пакета, собственно ipsec-tools и racoon, поскольку мы используем pre-shared key для идентификация.
Заносим реквизиты в /etc/racoon/psk.txt
Приводим /etc/racoon/racoon.conf к следующему виду
Настраиваем политики шифрования трафика /etc/ipsec-tools.conf
Если все сделано правильно, то можно увидеть следующее:
Вам также может понравиться
Мониторинг состояния tcp-соединений в Nagios/Icinga
Отслеживать состояние tcp-соединений не всегда нужно, но иногда очень полезно. Я уже писал про это применительно к Zabbix. Сейчас для мониторинга я […]
Ускоряем Graphite-web
Я уже писал про graphite, я все еще считаю, что для time series нет ничего лучше. А так как начиная с версии […]
OpenSSH и эллиптическая криптография (ECC)
Криптография с открытым ключом или асимметричное шифрование существует уже давно. Наиболее попялрному алгоритму RSA вот уже почти 40 лет, алгоритм DSA в […]
Устанавливаем Puppet Dashboard
Я уже упоминал о Puppet, как о средстве централизованного управления парком серверов, теперь речь зайдет о Puppet Dashboard. Это веб-интерфейс предостовляющий наглядный […]
5 комментариев “ L2TP/IPSEC между роутером MikroTik и Ubuntu Linux ”
Кроме этого, не получается с пробросом порта на камеру в подсети опенврт.
На микротике открыл порт, смотрю торчем на л2тп интерфейс. запросы из вне идут. А назад нет.
Дело в маршрутах на оперврт я так понимаю? когда я с локалки микротика захожу все пашет, так как прописан маршрут.
а из когда из вне, трафик идёт через тунель, только в одну сторону, назад он не идёт.
я вижу 2 выхода. смаскарадить или маршрут по умолчанию поменять на тунель. только как это сделать?
Эту проблему поборол. на опенврт прописал в конфигах след.
config interface ‘vpn’
option ifname ‘ppp0’
option proto ‘none’
config zone
option name ‘lan’
option network ‘lan vpn’
option input ‘ACCEPT’
option output ‘ACCEPT’
option forward ‘ACCEPT’
На камеру удаленно заходит, видео еле-еле пашет на битрейте 80кбит, хотя сигнал стабильный. И если я поставлю в камере битрейт побольше, сначала пинги растут, потом туннель рвется, и восстанавливается через определенное время. Неужели l2tp такая нестабильная технология? в логах микротика —
logged out
terminating — administrator request
disconnected
Если туннель не грузить, он не падает.
Вопрос: Не знаешь, как сделать, чтобы при подключении туннеля на опенврт маршрут сам добавлялся…
пока, что приходится ручками route add -net 192.168.0/24 ppp0
Сделал по офф мануалу с микротик wiki site2site l2tp
прописал маршруты. сдвинулось, но не сильно,
с локалки микротика смог зайти в веб-интерфейс openwrt. а дальше на камеру зайти не смог( которая в локалке openwrt) не пингуется..
и вот ещё что заметил, если я пингую с локалки openwrt комп в локалке микротика, пинги не идут… а ели пинговать напрямую с самой opewrt то пинги проходят..
грешу на модем в режиме сетевой карты. где-то читал, что с ним и vpn могут быть проблемы.
Есть два варианта:
1. Локальная сеть ходит на удаленный сервер через l2tp с NAT, который не корректно настроен
2. Локальная сеть ходит на удаленный сервер через l2tp, при этом на удаленном сервере не прописан маршрут в локальную сеть через l2tp
P.S. C наступающим новым годом!
Привет, поднял xl2tpd на собранной openwrt со скриптами Huntsman (для 3g/4g модема — huawei e3276 — работает в режиме сетевой карты). роутер tp-link 842nd.
Соединился с микротиком по твоему мануалу, пока без шифрования.
Если пинговать удаленный сервер напрямую с микротика, то пинги проходят.
А с локальной сети не могу пропинговать, ssh и тд не работает — connection refused
Понимаю, что дело в микротике. пробовал proxy-arp на интерфейс бридж ставить и на лан2, ничего не меняется.
конфиг:
1. Локалка микротика — 192.168.1.0/24
2. Локалка openwrt — 192.168.2.0/24
3. l2tp — remote-adress — 192.168.3.2 local-adress — 192.168.3.1
PS: очень прошу помощи — это один из последних шагов в подключении ip камеры c хранилищем на роутере. ( видеоархив уже пишется) через 3g
Источник