Linux charon что это

Содержание
  1. strongSwan
  2. Contents
  3. Installation
  4. Certificates
  5. Certificate Authority
  6. Host Certificate
  7. Client Certificate
  8. VPN Variants
  9. IPSec in tunnel mode
  10. IPSec in transport mode
  11. IPSec/L2TP
  12. Secrets
  13. Networking
  14. Starting
  15. Running Strongswan in a Container
  16. Troubleshooting
  17. Routing issues
  18. SSL Handshake Timeouts
  19. Connection established but no traffic
  20. Обзор IPSEC демона StrongSwan
  21. Введение
  22. Обзор демона StrongSwan
  23. Настройка VPN сервера (GRE/IPSec StrongSwan, OSPF Quagga)
  24. Настройка файрвола и роутинга
  25. Настройка StrongSwan
  26. Старый способ, использующий демон strongswan, уже достаточно хорошо описан:
  27. Новый способ, использующий демон charon, появившийся в версии 5.2.0:
  28. Одинаковые настройки аутентификации и шифрования для всех. Сделаем разными только PSK:
  29. Индивидуальные настройки аутентификации и шифрования:
  30. Поднятие туннелей с маршрутизаторами Cisco
  31. Настраиваем GRE-туннели в CentOS
  32. Создаем туннель на Cisco 2951
  33. Создаем туннель на Cisco CSR1000V
  34. Настройка динамической маршрутизации на Quagga
  35. Настройка OSPF на CentOS
  36. Настройка OSPF на Cisco 2951
  37. Настройка OSPF на Cisco CSR1000V
  38. Что осталось нерассмотренным

strongSwan

IPSec is an encryption and authentication standard that can be used to build secure Virtual Private Networks (VPNs).

It is natively supported by the Linux kernel, but configuration of encryption keys is left to the user. The IKE protocols are therefore used in IPSec VPNs to automatically negotiate key exchanges securely using a variety of means, including certificates, pre-shared keys or both.

They are typically implemented in userspace daemons on the server side. strongSwan is an IKE daemon with full support for IKEv1 and IKEv2. It is natively supported by most modern clients, including Linux, Windows 7, Apple iOS, Mac OSX, FreeBSD and BlackBerry OS.

Contents

Installation

Certificates

The first step is to generate the X.509 certificates, including a certificate authority (CA), a server certificate, and at least one client certificate.

Certificate Authority

Let us start by creating a self-signed root CA certificate:

The result is a 4096 bit RSA private key strongswanKey.pem (line 2) and a self-signed CA certificate strongswanCert.pem (line 7) with a validity of 10 years (3650 days). The files are stored in PEM encoded format.

You can change the Distinguished Name (DN) to more relevant values for country (C), organization (O), and common name (CN), but you do not have to.

To list the properties of your newly generated certificate, type in the following command:

Host Certificate

This certificate will be used to authenticate the VPN server. Run the following commands:

The result is a 2048 bit RSA private key vpnHostKey.pem (line 2). In line 4 we extract its public key and pipe it over to issue vpnHostCert.pem (line 11), a host certificate signed by your CA. The certificate has a validity of two years (730 days). It identifies the VPN host by its Fully Qualified Domain Name (FQDN) (here: vpn.example.com ).

In addition, OS X 10.7.3 or older requires the ikeIntermediate flag, which we also added here.

Since the addition of these two flags probably will not hurt anyone, you should make sure you keep them there.

Let us take a look at the properties of our newly generated certificate.

Client Certificate

Any client will require a personal certificate in order to use the VPN. The process is analogous to generating a host certificate, except that we identify a client certificate by the client’s e-mail address rather than a hostname.

The result is a 2048 bit RSA private key ClientKey.pem (line 2). In line 6 we extract its public key and pipe it over to issue ClientCert.pem (line 10), the first client certificate signed by your CA. The certificate has a validity of two years (730 days) and identifies the client by its e-mail address (here: myself@example.com ).

Читайте также:  Работа с файловыми системами linux

Finally we will bundle all needed certificates and keys into a PKCS#12 file with a passphrase, which is the most convenient format for clients.

VPN Variants

The easiest configuration to get running with is IPSec in tunnel mode, described below.

IPSec in tunnel mode

VPN configuration can be found in /etc/ipsec.conf . The following contains the necessary options to build a basic, functional VPN server:

IPSec in transport mode

This article or section needs expansion.

Compared to tunnel mode, transport mode does not encrypt the original IP header from its point of view. This is useful if something else (i.e. GRE) has already encapsulated the original packet to be transported through a tunnel, before IPSec gets it. From the point of view of IPSec, the IP header it thinks is the original is actually the IP header already setup for the tunneling, and it will encrypt what is truly the original IP header as just part of the encapsulated packet payload, without realizing it’s doing it.

IPSec/L2TP

The L2TP/IPsec VPN client setup page describes how to setup a client to connect to an IPSec/L2TP server. This variant of an IPSec VPN has the advantage of allowing to tunnel non-IP packets, contrary to pure IPSec, but at the expense of having to run an additional L2TP daemon.

This article or section needs expansion.

Secrets

The server’s private key needs to be configured in /etc/ipsec.secrets , like the following example:

Whenever you edit /etc/ipsec.secrets while strongSwan is running, you must reload the file:

Networking

You’re almost done setting up your server. There are a few things left to make your VPN server properly route the VPN tunnel:

The VPN configuration above automatically assigns an IP address to the client using DHCP, so you need to have a working DHCP server. If the server is running on the same host as strongSwan, you may need to edit /etc/strongswan.d/charon/dhcp.conf like this:

You may also need to allow the following protocols in your firewall:

  • ESP (Encrypted Secure Payload): Standard IPSec traffic
  • UDP 4500: IPSec traffic in «NAT Traversal» mode
  • UDP 500: Key exchanges (IKE)

Starting

This article or section is out of date.

Finally, you can start and enable strongswan-starter.service .

Running Strongswan in a Container

For running strongswan in a container like systemd-nspawn you need the following service file:

Troubleshooting

This article or section needs expansion.

Routing issues

If you are having troubles with routing traffic from client (road warrior) to the remote network, try disabling the bypass-lan plugin on the server. This plugin is enabled by default in the official Arch package since version 5.6.0. See the associated issue in strongswan bugtracker.

SSL Handshake Timeouts

Some users have had intermittent SSL handshake timeouts, such as:

  • curl -v https://example.com getting stuck at «TLSv1.3 (OUT), TLS handshake, Client hello (1):»
  • Firefox stalling loading a page, showing «Performing a TLS handshake to www.example.com»

Some users have fixed (or worked around?) this problem by decreasing their network interface mtu to be in the 1422-1438 range, even if they do not need to do so without a VPN or when using OpenVPN. [1] [2]

Читайте также:  Install linux desktop on android

Lowering mtu could potentially cause other problems, so your mileage may vary. This fix/workaround will likely somewhat decrease internet and internal network performance. (But, SSL handshakes will stop stalling.) If you are using jumbo frames, this may significantly decrease internal network performance.

Check your interface’s mtu: (The one being used to connect to the VPN)

Consider this default (probably 1500) bad.

You can efficiently try to find a mtu that prevents an SSL timeout by repeating this process, perhaps starting with a really low trial-mtu like 1300, or lower if that still fails: (interface is the name shown above by ip link , not a full path like /dev/device )

If it succeeds enough times for you to be confident an intermittent failure should have happened, consider this mtu as good, and hit CTRL+C . Re-run the above commands with a trial-mtu halfway between this one and your closest known bad mtu.

If it gets stuck on a TLS handshake, consider this as bad, and hit CTRL+C . Re-run the above with halfway between this one and your closest known good mtu.

Connection established but no traffic

This article or section needs expansion.

In certain setups, like KDE, you might get a established connection using ipsec up but you cannot reach any outside machine. This could be due to the openresolv package not being installed. It’s an optional dependency, but it might be required for your situation.

Источник

Обзор IPSEC демона StrongSwan

Введение

Обзор демона StrongSwan

StrongSwan является демоном IPSEC, который поддерживает IKEv1 и IKEv2. На данный момент это развивающий продукт. Установка StrongSwan может быть выполнена из исходников или репазитория. Установка из исходников описана на сайте StrongSwan.
Установка из репазитория происходит без проблем командой:
Файлы конфигурирования по умолчанию хранятся в директории /etc/ и имеют следующие названия:

  • ipsec.conf – определяет параметры IPSEC-соединений и параметры подключений в целом;
  • ipsec.secrets – служит для хранения ссылок на сертификаты и ключи аутентификации;
  • strongswan.conf – для подключения криптографических алгоритмов и дополнительных функций.

Помимо этого во время установки программного обеспечения для хранения сертификатов и CRL-файлов используемых демонами pluto и charon создается директория /etc/ipsec.d, в которой находятся следующие каталоги:

  • private – содержит закрытые ключи RSA и ECDSA;
  • certs – содержит сертификаты X.509 и PGP;
  • crls – хранит список отозванных сертиифкатов;
  • cacerts – хранит доверенные сертификаты CA;
  • ocspcerts – содержит подписанные OCSP сертификаты;
  • reqs – содержит запросы на сертификаты в формате PKCS#10.

Файл /etc/ipsec.secrets содержит неограниченное количество следующих типов ключей (паролей):

  • RSA для определения пароля к сертификату открытого ключа;
  • ECDS для определения пароля к сертификату открытого ключа;
  • PSK для определения Pre-shared ключа;
  • EAP для учетных записей EAP;
  • NTLM для учетных записей NTLM;
  • XAUTH для учетных записей XAUTH;
  • PIN для пин-кода смарт-карт.

Соответственно поддерживаются все типы аутентификации.
Основные параметры команды ipsec, которая управляет подключениями StrongSwan:

  • start|restart|stop;
  • ipsec status|statusall — для просмотра состояния IPSEC-соединений;
  • up|down|route|unroute — для управления IPSEC-соединений.

Логи хранятся в /var/log/auth.log и /var/log/daemon.log.

Настройка Remote Access VPN на сертификатах
Генерация сертификатов

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

Читайте также:  History очистить историю linux

Создаем директорию для новых сертификатов и файл с серийником для OPENSSL

Генерируем сертификат для сервера:

При генерации сертификата обязательно нужно задать для серверного сертификата в openssl.cnf параметр subjectAltName=IP:
Генерируем сертификат для клиента:

Настройка StrongSwan

Основными файлами для настройки являются etc/ipsec.conf и ipsec.secrets.
Начнем с ipsec.conf

Более подробно ознакомиться с директивами данного файла можно по ссылке.

Настройка IPSEC подключения для Win7 и импорт сертификатов .

Дальше можно подключиться клиентом и проверить статус соединения командой ipsec statusall и просмотром логов, ну и в Windows должно быть успешно подключено VPN-соединение и пинги будут бегать.

Источник

Настройка VPN сервера (GRE/IPSec StrongSwan, OSPF Quagga)

Кто бы мог подумать, что развернуть часть серверов компании в Amazon было плохой идеей.

В итоге поставленная задача — сделать дополнительный VPN-туннель между Amazon и инфраструктурой в РФ.

Кроме простого how-to опишу несколько особенностей в настройке, с которыми можно столкнуться.

Настройка файрвола и роутинга

Покупаем у пока еще не заблокированного хостера VPS за сумму, эквивалентную 10 000 монгольских тугриков в месяц, ставим CentOS 7, включаем пересылку пакетов

Добавляем в файрволе правила для приема пакетов IPsec

Настройка StrongSwan

Устанавливаем демон IPsec StrongSwan:

Делаем предварительные настройки в /etc/strongswan.d/charon.conf:

Настройка Strongswan может быть проведена двумя способами.

Старый способ, использующий демон strongswan, уже достаточно хорошо описан:

Файл с паролями и сертификатами:

Новый способ, использующий демон charon, появившийся в версии 5.2.0:

Вся конфигурация хранится в /etc/strongswan/swanctl/swanctl.conf

Рассмотрим два варианта настройки демона charon:

Одинаковые настройки аутентификации и шифрования для всех. Сделаем разными только PSK:

Индивидуальные настройки аутентификации и шифрования:

Поднятие туннелей с маршрутизаторами Cisco

Настраиваем GRE-туннели в CentOS

В настройке GRE-интерфейсов есть пара особенностей.

Первая — необходимо уменьшить MTU для корректного прохождения пакетов.

Второе — указать TTL, это понадобится в будущем, когда будем настраивать OSPF. Если этого не сделать, пакеты OSPF будут приходить на удаленный хост с TTL, равным единице (из-за GRE over IPsec), оставаясь без ответа. Соответственно устройства будут висеть в состоянии INIT/DROTHER, связности мы не дождемся. При этом корректные ответы ICMP могут сбить с толку.

Создаем туннель на Cisco 2951

Создаем туннель на Cisco CSR1000V

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

Настройка динамической маршрутизации на Quagga

Если вы используете динамическую маршрутизацию на основе OSPF, то следующим шагом логично было бы поднять демон OSPF на CentOS, настроив новые туннели в качестве резервного маршрута.

Настройка OSPF на CentOS

В качестве демона установим Quagga:

Создаем конфигурационный файл демона /etc/quagga/zebra.conf

Вес пути можно регулировать параметрами cost либо bandwidth, устанавливая их на нужных интерфейсах.

Устанавливаем права и включаем службу

Создаем конфигурационный файл демона /etc/quagga/ospfd.conf

Устанавливаем права и включаем службу

Далее можем запустить терминал vtysh и работать с Quagga в циско-подобном интерфейсе, например:

Настройка OSPF на Cisco 2951

Настройка OSPF на Cisco CSR1000V

Проверяем видимость соседей и пришедшие маршруты на CentOS:

Что осталось нерассмотренным

Я описал самый простой вариант. Конечно же, вы настроите обмен ключами, используя IKE v2, авторизацию по сертификату, добавите в файрвол дополнительную фильтрацию по адресам, сделаете OSPF с авторизацией и, при большом количестве маршрутизаторов, с разделением на area, измените значения hello-interval и dead-interval на интерфейсах.

Буду рад советам в комментариях, а информации об опечатках — в личку. Спасибо за внимание.

Источник

Оцените статью