Обзор ipsec демона strongswan

L2TP

Устанавливаем сервер L2TP:

apt-get install xl2tpd

Открываем файл настройки сервера:

vi /etc/xl2tpd/xl2tpd.conf

Добавляем:

port = 1701
access control = no
ipsec saref = yes
force userspace = yes
auth file = /etc/ppp/chap-secrets

ip range = 176.16.10.10-176.16.10.200
local ip = 176.16.10.1
name = l2tpserver
pppoptfile = /etc/ppp/options.xl2tpd
flow bit = yes
exclusive = no
hidden bit = no
length bit = yes
require authentication = yes
require chap = yes
refuse pap = yes

где:

  • port — порт UDP, на котором работает VPN. По умолчанию, 1701.
  • access control — принимать или нет запросы только от клиентов с определенными IP, перечисленными в настройках клиентов.
  • ipsec saref — указывает использовать или нет ipsec Security Association, позволяющий отслеживать несколько клиентов с одинаковыми IP-адресами.
  • force userspace — повышает производительность за счет декапсуляции пакетов L2TP.
  • auth file — путь к файлу аутентификации.
  • ip range — диапазон адресов, которые назначаются подключенным клиентам.
  • local ip — IP-адрес сервера в сети VPN.
  • name — имя сервера для процесса согласования.
  • pppoptfile — путь к файлу с настройкой pppd.
  • flow bit — позволяет добавлять в пакеты порядковые номера.
  • exclusive — если поставить в yes, сервер разрешит только одно соединение с клиентом.
  • hidden bit — скрывать или нет AVP.
  • length bit — использовать ли бит длины, указывающий полезную нагрузку.
  • require authentication — требовать ли аутентификацию.
  • require chap — требовать ли аутентификацию PPP по протоколу CHAP.
  • refuse pap — требовать ли аутентификацию PPP по протоколу PAP.

Разрешаем автозапуск vpn-сервера и перезапускаем его:

systemctl enable xl2tpd

systemctl restart xl2tpd

NAT configuration

Before we can even begin to connect our two networks using a Virtual Private Network (VPN)
we need to make some configuration changes to the NAT device(s). When NAT
Traversal (NAT-T) is enabled the racoon daemon will need to be able
to receive UDP packets on ports 500 and 4500
to function correctly. To achieve this you will need to configure port forwarding,
or application sharing as it is sometimes known on consumer grade routers, to send any
traffic to these ports to the gateway host. You will also need to ensure that this mapping is preserved
after the gateway host or the NAT device are restarted to ensure that the
VPN will still function after these events. This will usually require the use of
static address assignment to ensure that the gateway host always receives the same
private network address.

Step 4 — Configuring StrongSwan

We’ve already created all the certificates that we need, so it’s time to configure StrongSwan itself.

StrongSwan has a default configuration file, but before we make any changes, let’s back it up first so that we’ll have a reference file just in case something goes wrong:

The example file is quite long, so to prevent misconfiguration, we’ll clear the default configuration file and write our own configuration from scratch. First, clear out the original configuration:

Then open the file in your text editor:

First, we’ll tell StrongSwan to log daemon statuses for debugging and allow duplicate connections. Add these lines to the file:

/etc/ipsec.conf

Then, we’ll create a configuration section for our VPN. We’ll also tell StrongSwan to create IKEv2 VPN Tunnels and to automatically load this configuration section when it starts up. Append the following lines to the file:

/etc/ipsec.conf

Next, we’ll tell StrongSwan which encryption algorithms to use for the VPN. Append these lines:

/etc/ipsec.conf

We’ll also configure dead-peer detection to clear any “dangling” connections in case the client unexpectedly disconnects. Add these lines:

/etc/ipsec.conf

Then we’ll configure the server (left) side IPSec parameters. Add this to the file:

/etc/ipsec.conf

Note: When configuring the server ID (), only include the character if your VPN server will be identified by a domain name:

If the server will be identified by its IP address, just put the IP address in:

Then we configure the client (right) side IPSec parameters, like the private IP address ranges and DNS servers to use:

/etc/ipsec.conf

Finally, we’ll tell StrongSwan to ask the client for user credentials when they connect:

/etc/ipsec.conf

The configuration file should look like this:

/etc/ipsec.conf

Save and close the file once you’ve verified that you’ve configured things as shown.

Now that we’ve configured the VPN parameters, let’s move on to creating an account so our users can connect to the server.

Conclusion

In this tutorial, you’ve built a VPN server that uses the IKEv2 protocol. Now you can be assured that your online activities will remain secure wherever you go!

To add or remove users, just take a look at Step 5 again. Each line is for one user, so adding or removing users is as simple as editing the file.

From here, you might want to look into setting up a log file analyzer, because StrongSwan dumps its logs into syslog. The tutorial  How To Install and Use Logwatch Log Analyzer and Reporter on a VPS has more information on setting that up.

You might also be interested in this guide from the EFF about online privacy.

7: Тестирование VPN-соединений в Windows, iOS и macOS

Теперь всё готово к работе. Пора протестировать настройку. Сначала скопируйте root сертификат на клиентские устройства, которые будут подключаться к VPN. Проще всего для этого подключиться к серверу и запросить содержимое файла сертификата:

Скопируйте вывод на компьютер, включая строки ——BEGIN CERTIFICATE—— и ——END CERTIFICATE——. Сохраните эти данные в файл с описательным именем (например, vpn_root_certificate.pem). Файл должен иметь расширение .pem.

В качестве альтернативы можно использовать SFTP.

Скопировав сертификат на компьютер, вы можете подключиться к VPN.

Подключение в Windows

Импортируйте сертификат root:

  1. Нажмите WINDOWS+R, чтобы открыть диалог Run, и введите mmc.exe, чтобы запустить консоль управления Windows.
  2. Из меню File перейдите в Add or Remove Snap-in, выберите в списке Certificates и нажмите Add.
  3. Чтобы к VPN мог подключиться любой пользователь, выберите Computer Account и нажмите Next.
  4. Настройка выполняется на локальном компьютере, потому нужно выбрать Local Computer и нажать Finish.
  5. В Console Root разверните Certificates (Local Computer) → Trusted Root Certification Authorities и выберите Certificates.
  6. В меню Action выберите All Tasks и нажмите Import, чтобы вызвать мастер импортирования сертификатов. Нажмите Next.
  7. В поле File to Import выберите файл сертификата, который вы скопировали ранее. Нажмите Next.
  8. Убедитесь, что в Certificate Store выбрано Trusted Root Certification Authorities. Нажмите Next.
  9. Нажмите Finish, чтобы импортировать сертификат.

Чтобы настроить VPN:

  • Запустите панель управления, перейдите в Network and Sharing Center.
  • Нажмите Set up a new connection or network и выберите Connect to a workplace.
  • Выберите Use my Internet connection (VPN).
  • Введите данные сервера VPN. Укажите домен или IP сервера в поле Internet address. В Destination name укажите описательное имя VPN-соединения. Нажмите Done.

Новое VPN-соединение появится в списке сетевых подключений. Выберите VPN и нажмите Connect. Укажите имя пользователя и пароль, нажмите Ok, после чего вы подключитесь к VPN.

Подключение в iOS

Чтобы настроить VPN-соединение на устройстве iOS:

  1. Отправьте себе электронное письмо с сертификатом root.
  2. Откройте письмо на устройстве iOS и нажмите на прикрепленный файл сертификата, нажмите Install и введите пароль. После завершения нажмите Done.
  3. Откройте Settings → General → VPN и выберите Add VPN Configuration. На экране появится окно настройки VPN.
  4. Нажмите Type и выберите IKEv2.
  5. В поле Description укажите короткое имя VPN-соединения на свое усмотрение.
  6. В полях Server и Remote ID укажите доменное имя или IP сервера. Поле Local ID можно оставить пустым.
  7. Введите имя пользователя и пароль в разделе Authentication и нажмите Done.
  8. Выберите только что созданное VPN-соединение, нажмите переключатель в верхней части страницы, и вы подключитесь.

Подключение в macOS

Чтобы импортировать сертификат:

  1. Дважды кликните на файл сертификата, чтобы открыть Keychain Access. Появится диалоговое окно с сообщением «Keychain Access is trying to modify the system keychain. Enter your password to allow this.»
  2. Введите пароль и нажмите Modify Keychain.
  3. Дважды кликните на новый сертификат VPN. На экране появится небольшое окно свойств, где можно указать уровень доверия. В IP Security (IPSec) выберите Always Trust. После этого снова будет запрошен пароль. Введите пароль, после чего эти параметры сохранятся автоматически.

Чтобы создать VPN-подключение:

  1. System Preferences → Network.
  2. Во всплывающем окне найдите Interface и выберите VPN, в VPN Type выберите IKEv2, укажите имя соединения.
  3. В поля Server и Remote ID введите домен или IP сервера. Поле Local ID оставьте пустым.
  4. Кликните на Authentication Settings, выберите Username и укажите имя пользователя и пароль пользователя VPN. Нажмите OK.
  5. Нажмите Connect, после чего будет создано соединение VPN.

Исправление ошибок и неполадок

Если вы не можете импортировать сертификат, убедитесь, что он находится в файле с расширением .pem, а не .pem.txt.

Если у вас не получается подключиться к VPN, проверьте правильность доменного имени сервера или IP-адреса. Домен или IP должен совпадать со значением, указанным в параметре common name (CN) во время создания сертификата. Если они не совпадают, вы не сможете подключиться к VPN. К примеру, если в сертификате (в CN) вы указали vpn.example.com, вы должны использовать домен vpn.example.com при создании подключения к VPN.

Если вы указывали доменное имя, тогда также нужно проверить параметры VPN и убедиться, что в leftid перед доменом стоит символ @:

Если же вы указывали IP, убедитесь, что символа @ перед адресом нет.

5.2.1

20.10.2014

Minor Release

100%

14 issues
 
(14 closed

0 open)

Version 5.2.1

The new charon-systemd IKE daemon implements an IKE daemon tailored for use with systemd. It avoids the dependency on ipsec starter and uses swanctl as configuration backend, building a simple and lightweight solution. Native systemd journal logging is supported.

Support for the new IKEv2 Fragmentation mechanism as defined byRFC 7383 has been added, which avoids IP fragmentation of IKEv2 UDP datagrams exceeding the network’s MTU size. This feature is activated by setting fragmentation=yes in ipsec.conf and optionally setting the maximum IP packet size with the charon.fragment_size parameter in strongswan.conf.

Support of the TCG TNC IF-M Attribute Segmentation specification proposal, which allows to transfer potentially huge attributes amounting to several megabytes of measurement data like the TCG/SWID Tag Inventory or IETF/Installed Packages attributes via the PA-TNC, PB-TNC and either PT-EAP or PT-TLS NEA protocol stack. By default segmented attributes are just reconstructed on the receiving side from the individual segments with the exeception of the three attribute types mentioned above which can be parsed and processed incrementally as the segments arrive one-by-one. A commented example can be found under PT-EAP-SWID.

For the vici plugin a ruby gem has been added to allow ruby applications to control or monitor the IKE daemon. The vici documentation has been updated to include a description of the available operations and some simple examples using both the libvici C interface and the ruby gem (see README.md).

The new ext-auth plugin calls an external script to implement custom IKE_SA authorization logic, courtesy of Vyronas Tsingaras.

Paths to the ipsec.conf and ipsec.conf configuration files may be configured via strongswan.conf. The path to strongswan.conf may be passed via theSTRONGSWAN_CONF environment variable. Patches courtesy of Shea Levy.

Support for IKEv1 fragmentation has been extended to Windows XP/7 clients, courtesy of Volker Rümelin.

A static interval for interim RADIUS accounting updates can be configured for the eap-radius plugin. It’s overridden by any interval the RADIUS server returns in the Access-Accept message, but it can be useful if RADIUS is only used for accounting.

Fixed re-authentication when using IKEv1 Mode Config in push mode (cb98380fe9e4).

Handle Quick Mode DELETES during a Quick Mode rekeying (cd9bba508bba).

Fixed some Cisco Unity corner cases (rekeying and situations where no split-include attributes are received), one fix didn’t made it into this release though (#737).

Fixed some IKEv1 interoperability issues (e.g. with proposal numbering and IPComp), see #661.

Fixed a crash during reauthentication with multiple authentication rounds caused by the incorrect use of array_remove_at() in auth_cfg_t (8ca9a67fac59). Also added a comment regarding the used of that function (see c641974de001).

The kernel-pfkey plugin now reports packet counts (25fcbab6789c).

If available the kernel-pfroute plugin uses RTM_IFANNOUNCE/IFAN_DEPARTURE events to delete cached interfaces (see f80093e2ee65).

The kernel-netlink plugin can set MTU and MSS on installed routes via settings instrongswan.conf (these are global and affect all SAs).

The kernel-netlink plugin optionally installs protocol and ports on transport mode SAs (90e6675a657c) to enforce policies for inbound traffic. Enabling this prevents the use of a single IPsec SA by more than one traffic selectors though.

IPv6 transport via libipsec has been fixed (15dee933de7d).

TESTS_SUITES_EXCLUDE option added to unit test runner.

Added the source:testing/scripts/build-strongswan script to (relatively) quickly (re-)build strongSwan in the testing environment.

Don’t wait for charon if ipsec start —attach-gdb is used (f51c923f69f9, 508f90131a32).

Общие сведения об IPSEC

IPSEC, в общем случае, служит для поддержки безопасных соединений между узлами и сетями в глобальной сети Интернет. Он может работать в конфигурации «узел-узел» (один компьютер соединяется с другим) или «сеть-сеть» (одна локальная/глобальная сеть соединяется с другой). Реализация IPsec использует протокол обмена ключами в Интернете (Internet Key Exchange, IKE), разработанный комитетом по техническому развитию Интернета (Internet Engineering Task Force, IETF) для взаимной проверки подлинности и соответствия параметров безопасности между подключающимися системами или сетями.

Процесс соединения IPsec разделяется на два логических этапа. На первом этапе узел IPsec устанавливает подключение к удалённому узлу или сети. Удалённый узел/сеть проверяет учётные данные запрашивающего узла и обе стороны согласуют способ проверки подлинности, применяемый в соединении. Обычно для проверки подлинности узла IPSec используется алгоритм с предварительным общим ключом. В случае с IPsec-соединением с применением предварительного общего ключа, оба узла должны использовать один ключ, и тогда они смогут перейти ко второму этапу установки соединения.

Второй этап соединения IPsec между узлами IPSec создаётся условным сравнением безопасности (security association, SA). При этом в базу данных SA вносится информация о конфигурации — метод шифрования, способы обмена секретными ключами сеанса и некоторые другие параметры. Этот этап и управляет соединением IPsec между узлами и сетями, разнесенными в пространстве глобальной сети.

Рассмотрим реализацию протокола IPSEC на примере дистрибутива CentOS Linux. Для развертывания IPSEC на всех машинах сети (в случае конфигурации «узел-узел») или маршрутизаторах (в случае конфигурации «сеть-сеть») необходимо установить соответствующие пакеты, управляющие конфигурацией IPSEC. В эти пакеты должны входить базовые библиотеки, демоны и файлы конфигурации, помогающие настроить соединение IPsec, в том числе — — библиотека, содержащая интерфейс управления доверенным ключом PF_KEY между ядром Linux и реализацией IPsec, используемой в CentOS Linux. При этом:

  • — настраивает управление ключами и атрибуты безопасности IPsec в ядре. Эта программа подчиняется демону , управляющему ключами. Дополнительная информация о setkey может быть найдена в man (8).
  • — демон управления ключами IKE, заведует обменом ключами и сопоставлением безопасности между компьютерами, реализующими IPsec. Настроить этот демон можно, отредактировав файл . За дополнительными сведениями о racoon, можно обратиться к странице man (8).
  • — файл конфигурации , в котором настраиваются различные параметры соединения IPsec, в том числе методы проверки подлинности и алгоритмы шифрования. Опять же, исчерпывающие данные по этому вопросу могут быть получены при изучении вывода команды man (5).
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector