Ipsec ikev2 rsa android

Почему я люблю IKEv2 больше других VPN

Сейчас все вокруг настраивают VPN для удаленных сотрудников. Мне больно смотреть, как люди устанавливают монструозные глючные программы, настраивают какие-то сертификаты, устанавливают драйвера TUN/TAP и делают множество сложных операций, в то время как лучшее решение уже встроено в операционную систему.

IKEv2 — это современный протокол VPN, разработанный Microsoft и Cisco. Он используется по умолчанию для новых VPN-подключений в Windows, macOS, iOS. Он быстрее и безопаснее большинства VPN-протоколов и может легко настраиваться на стороне клиента в два клика без использования сторонних программ.

Я считаю, что IPsec IKEv2 отлично подходит не только для соединения серверов, но и для обычных VPN-подключений конечных пользователей. В этом посте я постараюсь убедить вас использовать IPsec IKEv2 для обычных домашних пользователей вместо OpenVPN.

IKEv2 быстрее

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

Дело в том, что IPsec работает в контексте ядра операционной системы, а OpenVPN в контексте пользователя (userspace), и на обработку каждого пакета происходит переключение контекста между процессами ядра и процессами пользователя. Это влияет как на пропускную способность, так и на задержки.


Сравнение задержек для разных протоколов VPN.

Скриншот выше показывает разницу в задержке в два раза между IPsec и OpenVPN. Разумеется, разницу в 1мс невозможно заметить на глаз, но при нагрузке на систему эти значения могут значительно изменяться. Кроме того, реальные показатели сильно зависят от характеристик конкретной системы, поэтому я не буду приводить абсолютные цифры для сравнения двух протоколов. Задержки очень важны при использовании голосовой и видеосвязи через VPN.

По моим субъективным ощущениям IKEv2 на Windows 10 работает заметно отзывчивее чем OpenVPN. Ведь реальное использование десктопного компьютера сильно отличается от синтетических тестов VPN-протоколов. Нагрузка на процессор и память непостоянная, пользователь может запускать ресурсоемкие программы, все это будет влиять на показатели.

IKEv2 проще в настройке

Все современные операционные системы (кроме Android) поддерживают IPsec IKEv2 прямо из коробки. Не нужно устанавливать никакие программы, драйвера виртуальных адаптеров TUN/TAP и прочее. Всё управление VPN происходит из системного меню.

При этом настройку на клиенте можно упростить до трех строчек:

  • Домен — для IPsec домен обязателен, так как для него выпускается SSL-сертификат
  • логин
  • пароль

Не нужно больше передавать клиенту файлы с сертификатами и ключами, заставлять его импортировать корневые сертификаты в системное хранилище. Достаточно логина и пароля, при этом соединение будет так же надежно защищено, как и в OpenVPN при использовании сертификатов, ведь для установки соединения используется такой же x.509 сертификат, как и для веб-сайтов с HTTPS.

Настройка на Windows 10

Мастер настройки VPN вызывается из меню подключения к WiFi. С настройкой одного окна справится пользователь любой квалификации. Созданное подключение активируется из меню со списком WiFi-сетей.


Интерфейс настройки нового IKEv2 подключения в Windows 10

В macOS поддерживается IKEv2 начиная с версии 10.11 (El Capitan). Создание подключения происходит через меню настроек сети.

Добавляем новое подключение. В качестве имени подключения задаем любое произвольное имя.

Для проверки подлинности сертификата, нужно указать доменное имя. При этом в поле «Server Address» можно указать IP-адрес сервера, а домен только в «Remote ID», тогда для подключения не будет выполняться DNS-резолв, и оно будет происходить чуть быстрее.

Логин и пароль пользователя указываем из файла /etc/ipsec.secrets

Настройку iOS можно выполнить вручную через мастер, но намного удобнее использовать профиль автоконфигурации mobileconfig.

Ручная настройка по смыслу аналогична десктопной macOS:

Настройки -> VPN -> Добавить конфигурацию VPN

IKEv2 это безопасно

На предыдущем шаге мы выяснили, что для настройки подключения достаточно логина и пароля. Но как клиенту проверить, что подключение не прослушивается, не подменяются данные и сервер действительно тот, за кого себя выдает? Для этого используются обычные SSL-сертификаты, которые мы привыкли использовать для веб-сайтов и HTTPS.

Читайте также:  About android mini pc

Клиент устанавливает защищенный SSL-тоннель с сервером, и уже внутри него передается логин-пароль. По умолчанию в Windows и macOS для передачи пароля используется алгоритм mschapv2. Таким образом с помощью SSL-сертификата клиент проверяет подлинность сервера, а по логину-паролю сервер проверяет подлинность клиента.

Сервер IKEv2 может использовать один и тот же сертификат вместе с веб-сервером, например от популярного Let’s Encrypt. Это сильно упрощает управлением сертификатами.

Такая же модель используется в OpenVPN, и при желании в нем можно использовать сертификат от Lets Encrypt, однако администратору в любом случае потребуется передать пользователю файл для настройки VPN.

Настраиваем IKEv2 сервер

Развернуть свой IKEv2 сервер можно за пару минут с помощью скриптов автоматической установки или используя готовые контейнеры. Использовать docker не рекомендуется, так как его сетевая подсистема снижает производительность IPsec на дешевых тарифах VPS. Вы также можете настроить IKEv2-сервер вручную, на Хабре есть статьи с примерами настройки сервера Strongswan.

Мы будем использовать один из наиболее удачных вариантов скриптов автонастройки github.com/jawj/IKEv2-setup
Этот скрипт хорош тем, что использует сертификаты от Lets Encrypt и автоматически генерирует валидный сертификат.

Шаг 1: Выбор сервера

Для запуска VPN сервера нам потребуется VDS. Подойдет самая простая конфигурация с одним ядром процессора. Скрипт из нашего примера лучше всего протестирован на Ubuntu 18.04, поэтому при создании сервера выбираем этот образ ОС.

Ждем окончания установки сервера и копируем реквизиты для подключения. Пароль root придет на почту, либо его можно задать вручную через веб-интервейс. Далее все команды мы вводим

Шаг 2: Установка Strongswan

Подключаемся SSH-клиентом и запускаем скрипт установки:

Шаг 3: Настройка клиента

Введенные реквизиты пользователя VPN теперь нужно использовать для настройки на клиенте. Важно использовать именно то доменное имя, которое вы вводили в Hostname for VPN.

Шаг 4: Добавление новых пользователей

Чтобы добавить нового пользователя в уже созданный сервер, отредактируйте файл /etc/ipsec.sectes.

После добавления пользователя выполните команду ipsec secrets чтобы Strongswan перечитал конфиг.

Заключение

Мы рассмотрели удобство IKEv2 со стороны пользователя. Администрирование такого сервера не сложнее, а иногда даже проще чем OpenVPN. Если вы только планируете организовать удаленный доступ для своих сотрудников, обязательно посмотрите в сторону IKEv2. Не заставляйте своих пользователей устанавливать лишние программы, если все необходимое уже есть на их компьютере. Это удобнее, безопаснее и намного прогрессивнее.

Источник

IKEv2 from Android strongSwan to Cisco IOS with EAP and RSA Authentication

Available Languages

Download Options

Contents

Introduction

This document describes how to configure the mobile version of strongSwan in order to access a Cisco IOS ® software VPN gateway via the Internet Key Exchange Version 2 (IKEv2) protocol.

Three examples are presented:

  • Android phone with strongSwan that connects to the Cisco IOS software VPN gateway with Extensible Authentication Protocol — Message Digest 5 (EAP-MD5) authentication.
  • Android phone with strongSwan that connects to the Cisco IOS software VPN gateway with certificate authentication (RSA).
  • Android phone with strongSwan that connects to the Cisco IOS software VPN gateway behind Network Address Translation (NAT). There is a requirement to have two x509 extensions Subject Alternative Name in the VPN gateway certificate.

Cisco IOS software and strongSwan limitations are also included.

Prerequisites

Requirements

Cisco recommends that you have knowledge of these topics:

  • Basic knowledge of OpenSSL configuration
  • Basic knowledge of Cisco IOS software command-line interface (CLI) configuration
  • Basic knowledge of IKEv2

Components Used

The information in this document is based on these software and hardware versions:

  • Android 4.0 or later with strongSwan
  • Cisco IOS Software Release 15.3T or later
  • Cisco Identity Services Engine (ISE) Software, Version 1.1.4 and later

The information in this document was created from the devices in a specific lab environment. All of the devices used in this document started with a cleared (default) configuration. If your network is live, make sure that you understand the potential impact of any command.

Configure

Notes:

The Output Interpreter Tool (registered customers only) supports certain show commands. Use the Output Interpreter Tool in order to view an analysis of show command output.

Refer to Important Information on Debug Commands before you use debug commands.

Читайте также:  Очистить историю вайбер андроид как

Network Diagram

Android strongSwan establishes an IKEv2 tunnel with a Cisco IOS software gateway in order to access internal networks securely.

Certificate Enrollment

Certificates are a prerequisite for both EAP-based and RSA-based authentication.

In the EAP authentication scenario, a certificate is needed only on the VPN gateway. The client connects to the Cisco IOS software only when the software presents a certificate signed by a Certificate Authority (CA) that is trusted on Android. An EAP session then starts for the client to authenticate to the Cisco IOS software.

For RSA-based authentication, both endpoints must have a correct certificate.

When an IP address is used as a peer-ID, there are additional requirements for the certificate. Android strongSwan verifies if the IP address of the VPN gateway is included in the x509 extension Subject Alternative Name. If not, Android drops the connection; this is a good practice as well as a recommendation of RFC 6125.

OpenSSL is used as a CA because the Cisco IOS software has a limitation: it cannot generate certificates with an extension that includes an IP address. All certificates are generated by OpenSSL and imported to Android and the Cisco IOS software.

In the Cisco IOS software, the subject-alt-name command can be used in order to create an extension that includes an IP address, but the command works only with self-signed certificates. Cisco Bug ID CSCui44783, «IOS ENH PKI ability to generate CSR with subject-alt-name extension,» is an enhancement request to allow the Cisco IOS software to generate the extension for all types of enrollments.

This is an example of the commands that generate a CA:

conf_global.crt is a configuration file. The CA extension should be set to TRUE:

The commands that generate a certificate are very similar for Cisco IOS software and Android. This example assumes that there is already a CA used to sign the certificate:

conf_global_cert.crt is a configuration file. The Alternate Subject Name extension is a key setting. In this example, the CA extension is set to FALSE:

A certificate should be generated for both the Cisco IOS software and Android.

The IP address 10.48.64.15 belongs to the Cisco IOS software gateway. When you generate a certificate for the Cisco IOS software, make sure the subjectAltName is set to 10.48.64.15. Android validates the certificate received from Cisco IOS software and tries to find its IP address in the subjectAltName.

Cisco IOS Software

The Cisco IOS software needs to have a correct certificate installed for both RSA-based and EAP-based authentication.

The pfx file (which is a pkcs12 container) for the Cisco IOS software can be imported:

Use the show crypto pki certificates verbose command in order to verify that the import succeeded:

Android

For EAP-based authentication, Andorid needs to have just the correct CA certificate installed.

For RSA-based authentication, Andorid needs to have both the CA certificate and its own certificate installed.

This procedure describes how to install both certificates:

    Send the pfx file by email, and open it.

Provide the password that was used when the pfx file was generated.

Provide the name for the imported certificate.

Navigate to Settings >Security >Trusted Credentials in order to verify the certificate installation. The new certificate should appear in the user store:

At this point, a user certificate as well as a CA certificate are installed. The pfx file is a pkcs12 container with both the user certificate and the CA certificate.

Android has precise requirements when certificates are imported. For example, for a CA certificate to be imported successfully, Android requires that the x509v3 extension Basic Constraint CA be set to TRUE. Thus, when you generate a CA or use your own CA, it is important to verify that it has the correct extension:

EAP Authentication

Cisco IOS Software Configuration for EAP Authentication

IKEv2 allows the use of an EAP protocol stack in order to perform user authentication. The VPN gateway presents itself with the certificate. Once the client trusts that certificate, the client responds to the EAP request identity from the gateway. The Cisco IOS software uses that identity and sends a Radius-Request message to the authentication, authorization, and accounting (AAA) server, and an EAP-MD5 session is established between the supplicant (Android) and the authentication server (Access Control Server [ACS] or ISE).

Читайте также:  Топ планеров для андроид

After successful EAP-MD5 authentication, as indicated by a Radius-Accept message, the Cisco IOS software uses the configuration mode in order to push the IP address to the client and continue with traffic selector negotiation.

Notice that Android has sent IKEID=cisco (as configured). This IKEID received on the Cisco IOS software matches ‘ikev2 profile PROF’.

Android Configuration for EAP Authentication

Android strongSwan must have EAP configured:

    Disable automatic certificate selection; otherwise, 100 or more CERT_REQs are sent in the third packet.

Choose a specific certificate (CA) that was imported in the previous step; the username and password should be the same as on the AAA server.

EAP Authentication Test

In the Cisco IOS software, these are the most important debugs for EAP authentication. Most output has been omitted for clarity:

The Android logs indicate:

This example shows how to verify status on the Cisco IOS software:

These figures show how to verify status on Android:

RSA Authentication

Cisco IOS Software Configuration for RSA Authentication

In Rivest-Shamir-Adleman (RSA) authentication, Android sends the certificate in order to authenticate to the Cisco IOS software. That is why the certificate map that binds that traffic to a specific IKEv2 profile is needed. User EAP authentication is not required.

This is an example of how RSA authentication for a remote peer is set:

Android Configuration for RSA Authentication

User credentials have been replaced by the user certificate:

RSA Authentication Test

In the Cisco IOS software, these are the most important debugs for RSA authentication. Most output has been omitted for clarity:

The Android logs indicate:

In the Cisco IOS software, RSA is used for both signing and verification; in the previous scenario, EAP was used for verification:

Status verification on Android is similar to that in the previous scenario.

VPN Gateway Behind NAT — strongSwan and Cisco IOS Software Limitations

This example explains a limitation of strongSwan certificate verifications.

Assume that the Cisco IOS software VPN gateway IP address is statically translated from 172.16.1.1 to 10.147.25.80. EAP authentication is used.

Assume also that the Cisco IOS software certificate has a Subject Alternative Name for both 172.16.1.1 and 10.147.25.80.

After successful EAP authentication, Android performs verification and tries to find the IP address of the peer that was used in Android configuration (10.147.25.80) in the Subject Alternative Name extension. The verification fails:

The logs indicate:

The failure occurred because Android can read only the first Subject Alternative Name extension (172.16.1.1).

Now, assume that the Cisco IOS software certificate has both addresses in Subject Alternative Name but in the reverse order: 10.147.25.80 and 172.16.1.1. Android performs validation when it receives the IKEID, which is the IP address of VPN gateway (172.16.1.1), in the third packet:

Now the log shows:

Thus, when Android receives the IKEID, it needs to find the IKEID in the Subject Alternative Name and can use only the first IP address.

Note: In EAP authentication, the IKEID sent by the Cisco IOS software is the IP address by default. In RSA authentication, the IKEID is the certificate DN by default. Use the identity command under the ikev2 profile in order to change these values manually.

Verify

Verification and test procedures are available within the configuration examples.

Troubleshoot

This section provides information you can use to troubleshoot your configuration.

strongSwan CA Multiple CERT_REQ

When the certificate setting on strongSwan is Automatic Selection (the default), Android sends CERT_REQ for all trusted certificates in the local store in the third packet . The Cisco IOS software might drop the request because it recognizes a large number of certificate requests as a Denial of Service attack:

Tunnel Source on DVTI

Although it is fairly common to set the tunnel source on a virtual tunnel interface (VTI), it is not necessary here. Assume the tunnel source command is under a dynamic VTI (DVTI):

After authentication, if the Cisco IOS software tries to create virtual access interface that is cloned from a virtual template, it returns an error:

Two seconds after the failure, the Cisco IOS software receives a retransmitted IKE_AUTH from Android. That packet is dropped.

Источник

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