Windows 7 l2tp aes

Время на прочтение6 мин

Количество просмотров251K

Недавно я озадачился поиском возможности создания шифрованного подключения к своему офису средствами L2TP/IPsec протокола. Задача усложнилась, когда, кроме Windows клиентов, появилась потребность пускать в сеть еще iOS и Android клиентов. В Интернете множество статей как проделать это на Windows Server с «внешним» IP-адресом. Но я хочу предложить сообществу реализацию стандартными средствами Windows 7/8 шифрованного L2TP тоннеля в локальную сеть с популярной, на мой взгляд, топологией.

Структура сети

Маленькая сеть из десяти Windows 7/8 клиентов с выделенным сервером на базе Windows Server 2008 Std (на него пока не обращаем внимание) и с доступом в Интернет средствами простого роутера. Для VPN сервера я выделил одну из машин на Windows 7 Pro. Далее будет описано два способа поднятия L2TP/IPsec сервера на Windows 7 Pro.

Windows 7 L2TP/IPsec AES 128-bit с использованием сертификата

  • Первым делом нужно сгенерировать сертификат компьютера и пользователя на VPN сервере.
    Для этого воспользуемся бесплатной утилитой Simple Authority.
    Устанавливаем, запускаем. Сразу программа предложит сгенерировать сертификат компьютера. Заполняем поля. Хаотично клацаем по клавиатуре, тем самым генерируя случайное число. Вводим пароль (лучше длиннее 8-ми символов, иначе могут быть глюки) Сертификат компьютера (CA) готов. Если пользователь не добавлен, то добавляем. Справа заполняем необходимые поля. Жмем «New certificate». После этого на рабочем столе появится два файла сертификатов с расширениями *.cer и *.p12
  • Установим сертификаты на наш VPN сервер.
    Для этого делаем Win+R(«Выполнить»), вводим mmc, жмем Enter. Откроется Консоль.
    Добавляем оснастку (Файл->Добавить удалить оснастку). Выбираем «Сертификаты». Жмем «Добавить». Выбираем пункт «учетной записи компьютера» при вопросе, где будет управлять эта оснастка сертификатами. Далее, «Личное»->Правой кнопкой мыши->Все задачи->Импорт->Выбираем файл сертификата с расширением *.p12 (именно его). Вводим пароль, ставим галку «Пометить этот ключ как экспортируемый». В категории «Личное» появится два сертификата. Тот сертификат, у которого поля «Кому выдан» и «Кем выдан» одинаковые, нужно перенести в категорию «Доверенные корневые центры сертификации».
  • Нужно убедиться в отсутствии параметра ProhibitIpSec=1.
    Идем в реестр (Win+R -> regedit). Ищем ветку HKLM\System\CurrentControlSet\Services\Rasman\Parameters. Если вышеуказанного параметра там нет или он равен 0, то все хорошо. Иначе, исправляем это.
  • Создаем входящее подключение.
    Идем в «Центр управления сетями и общим доступом»->«Изменение параметров адаптеров». Жмем клавишу Alt, сверху выпадет меню. Далее Файл->«Новое входящее подключение». Выбираем нужных пользователей, ставим галку «Через интернет… VPN». Выбираем нужные протоколы. На TCP/IP v4->Ставим галку «Разрешить доступ к локальной сети» и обязательно устанавливаем пул адресов, выдаваемых клиенту. После создания подключения обязательно откройте его свойства и во вкладке «Пользователи» проверьте наличие галки «Пользователи должны держать пароли в секрете»
  • Проверим, открылись ли нужные нам порты. Открываем командную строку и командой netstat /a /p udp смотрим, открылись ли UDP 1701 UDP 4500 UDP 500.

Создание клиентского подключения для этого способа

  • Установим сертификаты на нашего VPN клиента. Копируем с VPN сервера сертификаты, которые создали ранее. Устанавливаем их точно таким же способом, как и на сервере.
  • Создадим VPN подключение. Идем в «Центр управления сетями и общим доступом» -> Настройка нового подключения или сети. Далее «Подключение к рабочему месту» -> Использовать мое подключение к Интернет. Вводим адрес нашего VPN сервера. Подключение готово.
  • Настроим наше VPN подключение. Имя пользователя и пароль, думаю, вопросов не вызывают. Во вкладке «Безопасность» выбираем тип VPN L2TP/IPsec и в дополнительных параметрах выбираем «Использовать сертификат» и убираем галку «Проверить атрибуты имени сертификата». Шифрование ставим Обязательное и «Разрешаем следующие протоколы» проверки подлинности: MS-CHAPv2. Далее вкладка Сеть -> TCP/IPv4 свойства -> Дополнительно -> Убираем галку «Использовать основной шлюз».
  • Если не поднимается подключение. То на Windows 8 стоит попробовать такой ключ реестра HKLM\SYSTEM\CurrentControlSet\Services\IPsec создаем параметр DWORD с именем AssumeUDPEncapsulationContextOnSendRule и значением 2. Для Windows 7/Vista этот параметр нужно создать в HKLM\SYSTEM\CurrentControlSet\Services\PolicyAgent

Итоги этого способа

Для Windows клиентов это хороший способ реализации L2TP/IPsec, но когда дело доходит до iOS клиентов, задача расширяется. Проблема в том, что iOS могут подключаться по L2TP только с шифрованием по Заранее подготовленной ключевой фразе (Preshared Key), а по сертификату могут подключаться только к Cisco VPN. Второй способ расскажет, как решить эту проблему.

Windows 7 L2TP/IPsec Preshared Key с ESP 3DES шифрованием и контролем целостности

  • Вернемся к чудо-параметру ProhibitIpSec=1. Идем в Реестр, в ветку HKLM\System\CurrentControlSet\Services\Rasman\Parameters и создаем там параметр типа DWORD с именем ProhibitIpSec и присваиваем ему значение 1. После этого необходимо или перезагрузить ОС, или перезапустить службы RemoteAccess и RasMan. Этим действием мы отключаем локальную политику IP безопасности по-умолчанию для IPsec.
  • Создадим теперь новую политику безопасности IP. «Выполнить» -> mmc -> Добавить оснастку -> «Управление политикой IP-безопасности» и выбираем Локальный компьютер. Далее «Создать политику IP-безопасности». «Далее» -> Вводим имя -> Галку «Использовать правило по умолчанию» не ставим -> Далее -> «Изменить свойства» галку оставляем. Откроются свойства новой политики. Здесь убрать галку «использовать мастер» и «Добавить». Теперь по порядку о каждой вкладке:
    • Список IP-фильтров. Вводим имя, снимаем галку «Исп. мастер», «Добавить». Адрес источника: «Любой». Адрес назначения: «Любой». Вкладка протокол. В выпадающем списке выбираем UDP. Пакеты ИЗ этого порта: 1701. Пакеты НА любой порт. ОК, ОК и возвращаемся в список IP-фильтров. Здесь вновь созданный фильтр отмечаем «точкой» и переходим на следующую вкладку.
    • Действие фильтра. По аналогии. Имя, галку про мастер, «Добавить». Выбираем «Согласовать безопасность», «Добавить». Выбираем «Шифрование и обеспечение целостности. (ESP)». ОК. Смотрим, чтоб не стояло никаких галок ниже списка методов безопасности. ОК. Аналогично отмечаем точкой и переходим к очередной вкладке.
    • Тип подключения. Все сетевые подключения.
    • Параметры туннеля. Это правило не указывает туннель IPsec.
    • Методы проверки подлинности. Не обращаем пока внимание на Kerberos, жмем «Добавить». Выбираем «Использовать данную строку (Предварительный ключ)» и вводим наш заранее придуманный Ключ. ОК. И теперь можно удалить Kerberos. В этой же вкладке можно добавить проверку подлинности по Сертификату. Процесс генерации и установки Сертификата описан в первом способе.
  • Обязательно нужно назначить новую политику IP-безопасности. Правой кнопкой мыши по ней, «Назначить».

Создание клиентского подключения для этого способа

  • Отличается от создания клиентского подключения для первого способа только Дополнительными свойствами L2TP/IPsec, где вместо использования сертификата выбираем «… использовать общий ключ».

Доступ к VPN серверу

На роутере я использовал службу Dynamic DNS, т.к. внешний IP динамический. Для возможности подключения необходимо сделать проброс портов (Port Forwarding) для портов UDP 1701 UDP 4500 UDP 500 к нашему VPN серверу. Мы подобрались к финишному этапу, где нас ждет еще одна немаленькая проблема. Дело в том, что Windows 7/8 имеет ограничение на максимальное количество подключений для удаленного доступа, и оно равно 1. Такого ограничения нет на Windows Server. Тут и напрашивается фраза «А на фига ты тут всё это написал?!» Есть два способа решения. Первый: один хороший человек провел немаленькую работу и написал патч, снимающий ограничение для Windows 7 Pro SP1. Здесь подробно описан сам процесс поиска решения и присутствует патч. Второй: использовать Windows Server. Но использовать не так, как написано в большинстве статей, где говорится о назначении серверу Роли «Маршрутизации и удаленного доступа» и использовании специальных оснасток, в которых чёрт ногу сломит, а использовать вышеописанный метод. Он отлично работает на Windows Server без назначения специальных ролей и без ограничений на число подключений.

Переработанный материал:
  • Windows XP Pro as a L2TP IPSec VPN Server
  • VPN сервер L2TP на Windows 7
  • Конфигурация подключений L2TP/IPSec, использующих проверку подлинности на основе предварительного ключа
  • Роль сервера удаленного доступа или VPN-сервера: настройка сервера удаленного доступа или VPN-сервера

Перед настройкой VPN-подключения, в дереве пользователей откройте карточку нужного пользователя и установите флаг Разрешить удаленный доступ через VPN. Для этого перейдите в раздел Пользователи -> Учетные записи.

Не рекомендуем использовать для VPN-подключений кириллические логины.

Создание VPN-подключения в Windows 7

L2TP IPsec клиенты, находящиеся за одним NAT’ом, могут испытывать проблемы подключения если их более одного. Решить проблему может помочь . Рекомендуем вместо L2TP IPsec использовать IKEv2 IPSec.

Перед созданием VPN-подключения для протоколов SSTP, L2TP и IKEv2, следует установить корневой сертификат локально на компьютер:

1. Скачайте корневой сертификат Let’s Encrypt по ссылке ;

2. Нажмите Пуск, найдите и запустите mmc.exe;

3. Нажмите Файл -> Добавить или удалить оснастку:

4. Выберите Сертификаты и нажмите Добавить:

5. Установите флаг в строке учетной записи компьютера, нажмите Далее -> Готово -> ОК:

6. В окне Консоль появится пункт Сертификаты (локальный компьютер):

  • Выберите его и нажмите правой кнопкой мыши на пункте Доверенные корневые центры сертификации;

  • Далее Все задачи -> Импорт

  • В окне Мастер импорта сертификатов нажмите Далее -> Обзор -> Выберите скачанный в пункте 1 -> Далее -> Далее -> Готово.

Создание VPN-подключения

1. Выберите Сеть -> Центр управления сетями и общим доступом:

2. Нажмите Настройка нового подключения или сети:

3. Выберите Подключение к рабочему месту и Далее:

4. Нажмите Использовать мое подключение к интернету (VPN) и заполните следующие поля:

  • Интернет-адрес — впишите имя VPN-сервера, например vpn.test.ru

  • Имя местоназачения — напишите произвольное название подключения

Установите флаг в пункте Не подключаться сейчас, только выполнить установку для подключения в будущем

5. В окне Введите имя пользователя и пароль заполните соответствующие поля;

6. Нажмите Создать, далее Закрыть;

7. В окне Центр управления сетями и общим доступом, выберите в левом верхнем углу Изменение параметров адаптера:

8. Нажмите правой кнопкой мыши на созданное подключение, выберите Свойства:

9. В открывшемся окне выполните следующие действия:

  • На вкладке Сеть — снимите отметки со всех пунктов, кроме Протокол Интернета версии 4

  • На вкладке Безопасность:

    • в строке Тип VPN выберите нужный тип подключения

    • в строке Шифрование данных выберите обязательное(отключиться, если нет шифрования)

    • в строке Проверка подлинности выберите Разрешить следующие протоколы

    • При необходимости заполните Дополнительные свойства

10. Нажмите OK и закройте Центр управления сетями и общим доступом;

11. В трее нажмите Сеть. Откроется окно с созданным VPN-подключением;

12. Нажмите правой кнопкой мыши по подключению и выберите Подключить.

Ошибки работы VPN-подключений

Если VPN-подключение по протоколам IPSeс в Windows автоматически разрывается через 7 часов 45 минут и при подключении по IKEv2 возникает ошибка «Ошибка сопоставления групповой политики» или ошибка с кодом «13868»

Для восстановления связи подойдут следующие действия:

1. Переподключите соединение. В данном случае соединение восстановится, но через 7 часов 45 минут вновь будет автоматически разорвано. Если вы хотите, чтобы подключение не разрывалось автоматически, то выполните действия из следующего пункта.

2. Внесите изменения в реестр:

  • Откройте Редактор реестра.

  • Перейдите по пути HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\RasMan\Parameters.

  • Нажмите правой кнопкой мыши по параметру именем NegotiateDH2048_AES256 и нажмите Изменить.

  • В строке Значение укажите значение 1:

  • Перезагрузите Windows.

    Если параметра именем NegotiateDH2048_AES256 нет, то создайте его. Для этого:

  • Нажмите правой кнопкой мыши по свободному месту реестра в Parameters и выберите Создать -> DWORD:

  • Задайте имя NegotiateDH2048_AES256.

  • Нажмите правой кнопкой мыши по созданному файлу и выберите Изменить:

  • В строке Значение укажите значение 1:

3. Перезагрузите Windows.

Если вы не хотите, чтобы после подключения по VPN интернет-трафик до внешних ресурсов ходил через Ideco UTM, то в свойствах VPN-подключения Сеть/Протокол интернета TCP/IP версии 4/Дополнительно уберите флаг Использовать основной шлюз в удаленной сети. Далее, чтобы получить доступ к компьютерам за Ideco UTM, вручную пропишите маршруты.

оставьте флаг только в пункте Протокол Microsoft СНАР версии 2 (MS-CHAP v2)

ChAoS

Posts: 13
Joined: Wed Jul 29, 2015 1:59 pm

L2TP-IPSEC Win7 with AES256???

Hello,

with effort I set up my SoftEther VPN Server and enabled L2TP to support Windows clients without the must to install SoftEther VPN client.

From a Windows 7 machine I can connect via L2TP — it runs perfect :)

When I look into the Details of this connection on both sides I can see AEC-CBC (128) bit. But Windows since Vista also supports 192 and 256 bit AES.

I can not figure out where and how to enable it.

Must it be enabled in Softether or in Windows 7?

Thanks in advance


kh_tsang

Posts: 551
Joined: Wed Jul 24, 2013 12:09 pm

Re: L2TP-IPSEC Win7 with AES256???

Post

by kh_tsang » Fri Jul 31, 2015 9:36 am

I have no idea but I can see AES-CBC(256 bits) when using my own server.

[attachment=0]83.png[/attachment]

You do not have the required permissions to view the files attached to this post.


ChAoS

Posts: 13
Joined: Wed Jul 29, 2015 1:59 pm

Re: L2TP-IPSEC Win7 with AES256???

Post

by ChAoS » Fri Jul 31, 2015 9:53 am

kh_tsang wrote:
> I have no idea but I can see AES-CBC(256 bits) when using my own server.
>
> [attachment=0]83.png[/attachment]

Hi kh_tsang

thank you for your quick reply. I found out I had to switch the security level to maximum in windows 7 client. After that I got also 256 bits.

In properties of the connection in windows there is a tab -> security and within that there is the dropdown where you can set the security level.

Thanks again ;)


kh_tsang

Posts: 551
Joined: Wed Jul 24, 2013 12:09 pm

Re: L2TP-IPSEC Win7 with AES256???

Post

by kh_tsang » Fri Jul 31, 2015 10:08 am

Maybe Windows 10 connects using AES-CBC(256 bits) by default.


Автор
Сообщение

Зарегистрирован: 17 июн 2012, 20:41
Сообщения: 31

 L2TP для windows 7 и windows XP

Cisco IOS Software, C1900 Software (C1900-UNIVERSALK9-M), Version 15.2(3)T, RELEASE SOFTWARE (fc1)

Настроен L2TP. Подключается либо только Windows 7, либо только Windows XP в зависимости от того, какой метод шифрования стоит первым в crypto dynamic-map…

Сам конфиг:

Код:

vpdn enable
!
vpdn-group L2TP
 ! Default L2TP VPDN group
 accept-dialin
  protocol l2tp
  virtual-template 2
 no l2tp tunnel authentication
 ip pmtu
 ip mtu adjust
!

crypto isakmp policy 20
 encr 3des
 authentication pre-share
 group 2

!
crypto isakmp key <key> address 0.0.0.0       
crypto isakmp invalid-spi-recovery
crypto isakmp keepalive 10 periodic
!

crypto ipsec transform-set L2TP-TSET-AES esp-aes esp-sha-hmac
 mode transport
crypto ipsec transform-set L2TP-TSET-3DES esp-3des esp-md5-hmac
 mode transport
!
!
crypto dynamic-map L2TP-DYN-MAP 10
 set nat demux
 set transform-set L2TP-TSET-AES
crypto dynamic-map L2TP-DYN-MAP 20
 set nat demux
 set transform-set L2TP-TSET-3DES
!
crypto map L2TP-CMAP 10 ipsec-isakmp dynamic L2TP-DYN-MAP
!
interface Loopback1
 ip address 192.168.100.1 255.255.255.0
!
interface GigabitEthernet0/0
 ip address 192.168.0.1 255.255.255.0
 ip access-group IN in
 ip nat inside
 ip virtual-reassembly in
 duplex auto
 speed auto
!
interface GigabitEthernet0/1
 description Internet
 ip address 100.200.300.400 255.255.255.224
 ip access-group OUT in
 no ip redirects
 ip nat outside
 ip inspect OUTFW out
 ip virtual-reassembly in
 ip verify unicast reverse-path
 duplex auto
 speed auto
 crypto map L2TP-CMAP
!
interface Virtual-Template2
 description L2TP over IPSec Template
 ip unnumbered Loopback1
 ip nat inside
 ip virtual-reassembly in
 peer default ip address dhcp-pool PPTP-POOL
 no keepalive
 ppp mtu adaptive
 ppp authentication ms-chap-v2 chap callin
!

Сейчас конектится Windows 7 (XP — нет)

Для XP надо сделать так (меняем местами L2TP-TSET-3DES и L2TP-TSET-AES или ооставляем нужный):

Код:

!
crypto dynamic-map L2TP-DYN-MAP 10
 set nat demux
 set transform-set L2TP-TSET-3DES
crypto dynamic-map L2TP-DYN-MAP 20
 set nat demux
 set transform-set L2TP-TSET-AES

а тепрь Windows XP (Win7 — нет)

тоесть
L2TP-TSET-3DES — для windows XP
L2TP-TSET-AES — для Windows 7

Как заставить работать оба!??

В логах (ну, оно и понятно фаза 2 не согласована…):

Код:

Jul 20 10:39:42.812: ISAKMP:(1120):Input = IKE_MESG_INTERNAL, IKE_PHASE1_COMPLETE
Jul 20 10:39:42.812: ISAKMP:(1120):Old State = IKE_P1_COMPLETE  New State = IKE_P1_COMPLETE

Jul 20 10:39:42.820: ISAKMP (1120): received packet from 222.333.444.555 dport 4500 sport 42094 Global (R) QM_IDLE
Jul 20 10:39:42.820: ISAKMP: set new node -957161361 to QM_IDLE
Jul 20 10:39:42.820: ISAKMP:(1120): processing HASH payload. message ID = 3337805935
Jul 20 10:39:42.820: ISAKMP:(1120): processing SA payload. message ID = 3337805935
Jul 20 10:39:42.820: ISAKMP:(1120):Checking IPSec proposal 1
Jul 20 10:39:42.820: ISAKMP: transform 1, ESP_3DES
Jul 20 10:39:42.820: ISAKMP:   attributes in transform:
Jul 20 10:39:42.820: ISAKMP:      SA life type in seconds
Jul 20 10:39:42.820: ISAKMP:      SA life duration (VPI) of  0x0 0x0 0xE 0x10
Jul 20 10:39:42.820: ISAKMP:      SA life type in kilobytes
Jul 20 10:39:42.820: ISAKMP:      SA life duration (VPI) of  0x0 0x3 0xD0 0x90
Jul 20 10:39:42.820: ISAKMP:      encaps is 61444 (Transport-UDP)
Jul 20 10:39:42.820: ISAKMP:      authenticator is HMAC-MD5
Jul 20 10:39:42.820: ISAKMP:(1120):atts are acceptable.
Jul 20 10:39:42.820: ISAKMP:(1120):Checking IPSec proposal 1
Jul 20 10:39:42.820: ISAKMP: transform 2, ESP_3DES
Jul 20 10:39:42.820: ISAKMP:   attributes in transform:
Jul 20 10:39:42.820: ISAKMP:      SA life type in seconds
Jul 20 10:39:42.820: ISAKMP:      SA life duration (VPI) of  0x0 0x0 0xE 0x10
Jul 20 10:39:42.820: ISAKMP:      SA life type in kilobytes
Jul 20 10:39:42.820: ISAKMP:      SA life duration (VPI) of  0x0 0x3 0xD0 0x90
Jul 20 10:39:42.820: ISAKMP:      encaps is 61444 (Transport-UDP)
Jul 20 10:39:42.820: ISAKMP:      authenticator is HMAC-SHA
Jul 20 10:39:42.820: ISAKMP:(1120):atts are acceptable.
Jul 20 10:39:42.820: ISAKMP:(1120):Checking IPSec proposal 1
Jul 20 10:39:42.820: ISAKMP: transform 3, ESP_DES
Jul 20 10:39:42.820: ISAKMP:   attributes in transform:
Jul 20 10:39:42.820: ISAKMP:      SA life type in seconds
Jul 20 10:39:42.820: ISAKMP:      SA life duration (VPI) of  0x0 0x0 0xE 0x10
Jul 20 10:39:42.820: ISAKMP:      SA life type in kilobytes
Jul 20 10:39:42.820: ISAKMP:      SA life duration (VPI) of  0x0 0x3 0xD0 0x90
Jul 20 10:39:42.820: ISAKMP:      encaps is 61444 (Transport-UDP)
Jul 20 10:39:42.820: ISAKMP:      authenticator is HMAC-MD5
Jul 20 10:39:42.820: ISAKMP:(1120):atts are acceptable.
Jul 20 10:39:42.820: ISAKMP:(1120):Checking IPSec proposal 1
Jul 20 10:39:42.820: ISAKMP: transform 4, ESP_DES
Jul 20 10:39:42.820: ISAKMP:   attributes in transform:
Jul 20 10:39:42.820: ISAKMP:      SA life type in seconds
Jul 20 10:39:42.820: ISAKMP:      SA life duration (VPI) of  0x0 0x0 0xE 0x10
Jul 20 10:39:42.820: ISAKMP:      SA life type in kilobytes
Jul 20 10:39:42.824: ISAKMP:      SA life duration (VPI) of  0x0 0x3 0xD0 0x90
Jul 20 10:39:42.824: ISAKMP:      encaps is 61444 (Transport-UDP)
Jul 20 10:39:42.824: ISAKMP:      authenticator is HMAC-SHA
Jul 20 10:39:42.824: ISAKMP:(1120):atts are acceptable.
Jul 20 10:39:42.824: ISAKMP:(1120): IPSec policy invalidated proposal with error 256
Jul 20 10:39:42.824: ISAKMP:(1120): IPSec policy invalidated proposal with error 256
Jul 20 10:39:42.824: ISAKMP:(1120): IPSec policy invalidated proposal with error 512
Jul 20 10:39:42.824: ISAKMP:(1120): IPSec policy invalidated proposal with error 256
Jul 20 10:39:42.824: ISAKMP:(1120): phase 2 SA policy not acceptable! (local 100.200.300.400 remote 222.333.444.555)
Jul 20 10:39:42.824: ISAKMP: set new node 314419965 to QM_IDLE
Jul 20 10:39:42.824: ISAKMP:(1120):Sending NOTIFY PROPOSAL_NOT_CHOSEN protocol 3
        spi 708393104, message ID = 314419965
Jul 20 10:39:42.824: ISAKMP:(1120): sending packet to 222.333.444.555 my_port 4500 peer_port 42094 (R) QM_IDLE
Jul 20 10:39:42.824: ISAKMP:(1120):Sending an IKE IPv4 Packet.
Jul 20 10:39:42.824: ISAKMP:(1120):purging node 314419965
Jul 20 10:39:42.824: %CRYPTO-5-IPSEC_SETUP_FAILURE: IPSEC SETUP FAILED for local:222.333.444.555 local_id:222.333.444.555 remote:100.200.300.400 remote_id:windowsxp IKE profile:None fvrf:None fail_reason:IPSec Proposal failure fail_class_cnt:1
Jul 20 10:39:42.824: ISAKMP:(1120):deleting node -957161361 error TRUE reason «QM rejected»

20 июл 2012, 14:22

Black-Dragon

Зарегистрирован: 01 янв 1970, 03:00
Сообщения: 909

 Re: L2TP для windows 7 и windows XP

Может здесь найдется что-то полезное:

http://social.technet.microsoft.com/For … f9281e4fb/

В частности:

Цитата:

in Windows services check that Both «IKE and AuthIP IPSec Keying module» and «IPSec policy agent» is set to Automatic mode and by default is set to start

http://sourcedaddy.com/windows-7/weak-c … pl2tp.html

Цитата:

Support for weak or nonstandard cryptographic algorithms has been removed beginning with Windows Vista.

The removal of support for DES encryption and MD5 integrity checking for L2TP/IPsecbased VPN connections means that L2TP/IPsec-based VPN connections now support the following data encryption and data integrity algorithms by default:
128-bit AES, 256-bit AES, and 3DES for data encryption using IPsec
Secure Hash Algorithm (SHA1) for data integrity using IPsec

The removal of support for DES and MD5 from the default configuration means that L2TP/ IPsec-based VPN connections will not work if your existing VPN server supports only DES for data encryption and/or MD5 for data integrity checking.

Пока проверьте это, дальше посмотрим.
В любом случае, Win7 3DES поддерживает, а вот XP AES, кажется, нет. В то же время, оба поддерживают SHA1. => Надо юзать 3DES + SHA1.

20 июл 2012, 15:51

Dmitry[kiev]

Зарегистрирован: 17 июн 2012, 20:41
Сообщения: 31

 Re: L2TP для windows 7 и windows XP

Убрал лишнее, сделал следующее:

Код:

crypto ipsec transform-set L2TP-TSET-3DES esp-3des esp-sha-hmac
 mode transport
!
crypto dynamic-map L2TP-DYN-MAP 5
 set nat demux
 set transform-set L2TP-TSET-3DES
!
!
!
crypto map L2TP-CMAP 10 ipsec-isakmp dynamic L2TP-DYN-MAP
!

теперь не подключается ни XP, ни 7ка.

20 июл 2012, 16:41

Izobretatel

Зарегистрирован: 01 янв 1970, 03:00
Сообщения: 129

 Re: L2TP для windows 7 и windows XP

20 июл 2012, 23:07

Dmitry[kiev]

Зарегистрирован: 17 июн 2012, 20:41
Сообщения: 31

 Re: L2TP для windows 7 и windows XP

Не очень помогло: в принципе конфиг сделан похож, хотя и не асу конфигурируем.

Вроде же разобрались в чем проблема: в шифровании.
Конфигурируем два метода для XP и 7ки, но работает только один, указанный первым!

Не я первый кто делал эти конфигурации. Все делают теже два метода шифрования и что, только у меня не работает?

Почему в данной схеме срабатывает только первый криптомап!?:

Код:

!
crypto dynamic-map L2TP-DYN-MAP 10
 set nat demux
 set transform-set L2TP-TSET-AES
crypto dynamic-map L2TP-DYN-MAP 20
 set nat demux
 set transform-set L2TP-TSET-3DES
!
crypto map L2TP-CMAP 10 ipsec-isakmp dynamic L2TP-DYN-MAP
!

Это так должно быть или это только у меня?

21 июл 2012, 13:02

Black-Dragon

Зарегистрирован: 01 янв 1970, 03:00
Сообщения: 909

 Re: L2TP для windows 7 и windows XP

Dmitry[kiev] писал(а):

Почему в данной схеме срабатывает только первый криптомап!?:
!
crypto dynamic-map L2TP-DYN-MAP 10
set nat demux
set transform-set L2TP-TSET-AES
crypto dynamic-map L2TP-DYN-MAP 20
set nat demux
set transform-set L2TP-TSET-3DES
!
crypto map L2TP-CMAP 10 ipsec-isakmp dynamic L2TP-DYN-MAP
!

Я в сабже вообще ни хрена не понимаю, но может потому, что у вас только один криптомап?!

Попробуйте так (посмотрел в одном древнем конфиге у себя, пишу по аналогии):

Код:

crypto dynamic-map L2TP-DYN-MAP-4Seven 10
 set nat demux
 set transform-set L2TP-TSET-AES
!
crypto dynamic-map L2TP-DYN-MAP-4XP 10
 set nat demux
 set transform-set L2TP-TSET-3DES
!
crypto map L2TP-CMAP 10 ipsec-isakmp dynamic L2TP-DYN-MAP-4Seven
crypto map L2TP-CMAP 20 ipsec-isakmp dynamic L2TP-DYN-MAP-4XP

21 июл 2012, 14:06

Dmitry[kiev]

Зарегистрирован: 17 июн 2012, 20:41
Сообщения: 31

 Re: L2TP для windows 7 и windows XP

Не знаю почему, но самый первый конфиг, после перезагрузки роутера, заработал для обоих ОС и сейчас работает!

работает и не буду трогать!

20 авг 2012, 18:46

gvur

Зарегистрирован: 29 май 2013, 10:10
Сообщения: 2

 Re: L2TP для windows 7 и windows XP

Добрый день. Для корректной одновременной работы клиентов Windows 7 и Windows XP мне пришлось использовать конфигурацию, почти идентичную первоначальной. Все отличие заключается в следующем:

crypto dynamic-map L2TP-DYN-MAP 10
set nat demux
set transform-set L2TP-TSET-AES L2TP-TSET-3DES

crypto map L2TP-CMAP 10 ipsec-isakmp dynamic L2TP-DYN-MAP

Возможно, мое сообщение окажется несколько несвоевременным, однако надеюсь, что оно поможет кому-нибудь сберечь время и нервы.

29 май 2013, 10:13

Important
IPsec/L2TP is considered a legacy VPN protocol. For modern clients, (Windows since Windows 7, Android since 11, macOS since 10.11, iOS since 9) consider IPsec IKEv2 MSCHAPv2 VPN server instead. Note strongSwan can simultaneously handle legacy IKEv1/L2TP clients and modern pure IKEv2/MSCHAPv2 clients, if both need to be supported

Many operating systems support an L2TP/IPsec VPN out-of-the-box. By combining the confidentiality- and authentication services of IPsec (Internet Protocol security), the network tunneling of the Layer 2 Tunnel Protocol (L2TP) and the user authentication through pppd, administrators can define VPN networks across multiple, heterogeneous systems. This allows setting up a VPN across Android, Windows, Linux, MacOS and other operating systems without any commercial software requirements.

Introduction

IPsec/L2TP is a commonly used VPN protocol used in Windows and other operating systems. All version of Windows since Windows 2000 have support built-in, not requiring an external client (like OpenVPN does) making it very convenient. However, it is significantly harder to set up on the server side on Linux, as there’s at least 3 layers involved: IPsec, L2TP, and PPP.

  1. The IPsec setup provides the confidentiality of the network communication and the client (system) authentication
  2. With L2TP a tunnel is set up so that the VPN traffic goes over IPsec in a transparent manner
  3. The PPP (Point-to-Point Protocol) setup manages the authentication of the users

This guide will not cover setting up DHCP, RADIUS, Samba or a Public Key Infrastructure (PKI). It also does not really cover how to configure Linux clients, although the step to do so can be derived from the guide pretty easily. It does cover some Windows client configuration for the purpose of troubleshooting the server setup.

Assumptions and example settings

For the purpose of this guide, the following assumptions (or sample settings) are used:

  • Domain is example.com
  • Server name is vpn.example.com
  • CA file is called ca.crt
  • Server cert is vpn.example.com.crt
  • Server key is vpn.example.com.key
  • Client cert is client.example.com.crt
  • Client key is client.example.com.key

IPsec

The first layer to set up is IPsec. Note IPsec is peer-to-peer, so in IPsec terminology, the client is called the initiator and the server is called the responder.

There are 2 implementations of IPsec in Portage: LibreSwan and strongswan. Both have NAT traversal enabled by default, but if the VPN server is behind NAT and the client is Windows, special client configuration is required.

In the next sections, the different configurations are explained. For each option, document

  • how to use PSK for authentication, and
  • how to use certificates for authentication

Make sure to pick one (either PSK or certificates). Note there is no provision within the IKEv1 protocol to negotiate PSKs. The only information available to choose which key to use is based on the source and destination IP addresses. Since, in the usual scenario, the responder won’t know the initiator’s IP in advance, everyone must use the same pre-shared key. Therefore, certificates (PKI) are highly recommended over pre-shared keys (PSK), even for only a single user. However generating certificates and creating a PKI is a rather complex process and out of scope of this document, but the app-crypt/easy-rsa package can make it less painful.

For this tutorial, when using certificate based authentication, the necessary certificates are already available.

Option 1: LibreSwan

LibreSwan is a fork of Openswan (which itself a fork of FreeS/WAN). It is actually forked by the remaining original developers of Openswan, however after the original developers left Xelerance, a dispute about the «Openswan» name escalated to a lawsuit, after which the name LibreSwan was taken.

PSK setup for LibreSwan

A shared key must be created. It may either be specified by a quoted string or by a hex number. Based on the next example, PUT_VPN_SERVER_IP should be replaced by the server’s IP address. The domain name can be used, but it is not recommended by the LibreSwan developers. The %any setting allows any client to use this PSK.

FILE /etc/ipsec.d/vpn.example.com.secret

PUT_VPN_SERVER_IP %any : PSK 0x87839cfdab5f74bc211de156d2902d128bec3243
# Or to use a plain text key instead of hex:
# PUT_VPN_SERVER_IP %any : PSK "password_pass"

Then create /etc/ipsec.d/vpn.example.com.conf:

FILE /etc/ipsec.d/vpn.example.com.conf

conn vpnserver
        type=transport
        authby=secret
        ikev2=no
        pfs=no
        rekey=no
        keyingtries=1
        left=%defaultroute
        leftprotoport=udp/l2tp
        leftid=@vpn.example.com
        right=%any
        rightprotoport=udp/%any
        auto=add

Certificate based setup for LibreSwan

LibreSwan requires Network Security Services (NSS) to be properly configured and used for the certificate management. To make things easy, a PKCS#12 bundle should be created containing the server’s secret key, the server’s certificate and the CA certificate.

user $openssl pkcs12 -export -certfile ca.crt -inkey vpn.example.com.key -in vpn.example.com.crt -out /etc/ipsec.d/vpn.example.com.p12 -passout pass:

The bundle can then be imported into the NSS database:

root #pk12util -i vpn.example.com.p12 -d /var/lib/ipsec/nss

The LibreSwan configuration files will refer to the nickname for the imported objects. Use certutil -L -d /var/lib/ipsec/nss and certutil -K -d /var/lib/ipsec/nss to see what they are.

Above, vpn.example.com is used for the nickname obtained through the certutil -K -d . command.

FILE /etc/ipsec.d/vpn.example.com.conf

conn vpnserver
        type=transport
        authby=rsasig
        ikev2=no
        pfs=no
        rekey=no
        keyingtries=1
        left=%defaultroute
        leftprotoport=udp/l2tp
        leftcert=vpn.example.com
        leftid=@vpn.example.com
        right=%any
        rightprotoport=udp/%any
        rightrsasigkey=%cert
        auto=add

Here, vpn.example.com was the nickname obtained via the certutil -L -d . command.

Option 2: strongSwan

strongSwan is a fork of FreeS/WAN (although much code has been replaced).

While strongSwan supports the legacy (stroke) ipsec.conf configuration mechanism, it introduces a new kind of config file for a new
interface: the Versatile IKE Control Interface (VICI).

To use it, a few directories need to be defined:

root #( umask 007 ;\

mkdir /etc/swanctl/{bliss,conf.d,ecsda,pkcs12,pkcs8,private,pubkey,rsa};\
mkdir /etc/swanctl/x509{,aa,ac,ca,crl,ocsp};\
mkdir /etc/ipsec.d;\
mkdir /etc/ipsec.d/{private,certs,crls,ocspcerts,aacerts,acerts,reqs}; )


PSK setup for strongSwan

A shared key must be created. It may either be specified by a quoted string or by a hex number.

FILE /etc/swanctl/conf.d/vpn.example.com.conf

connections {
	linuxvpn {
		version=1
                proposals=aes128-sha1-modp1024,default
		local-1 {
			auth=psk
			id = @vpn.example.com
		}
		remote-1 {
			auth=psk
		}
		children {
			only {
				mode=transport
				local_ts=dynamic[udp/l2tp]
				rekey_time=0
			}
		}
	}
}
pools {
}
secrets {
	ike-1 {
		secret = "password_pass"
	}
}
authorities {
}

The proposals=aes128-sha1-modp1024,default is for Windows 7 and Android. Without it, they will be unable to connected. See the client notes below.

Certificate based setup for strongSwan

The files must be copied to the correct place:

root #cp ca.crt /etc/swanctl/x509ca

root #cp server.example.com.crt /etc/swanctl/x509

root #cp server.example.com.key /etc/swanctl/private

Finally update the /etc/swanctl/conf.d/vpn.example.com.conf file as follows:

FILE /etc/swanctl/conf.d/vpn.example.com.conf

connections {
	linuxvpn {
		version=1
                proposals=aes128-sha1-modp1024,default
		local-1 {
			auth = pubkey
			certs = vpn.example.com.crt
			id = @vpn.example.com
		}
		remote-1 {
			auth = pubkey
		}
		children {
			only {
				mode=transport
				local_ts=dynamic[udp/l2tp]
				rekey_time=0
			}
		}
	}
}
pools {
}
secrets {
}
authorities {
}

The proposals=aes128-sha1-modp1024,default is for Windows 7 and Android. Without it, they will be unable to connected. See the client notes below.

L2TP

The second layer, Layer 2 Tunneling Protocol (L2TP), is much easier to setup. Like IPsec, L2TP is a peer-to-peer protocol. The client side is called the L2TP Access Concentrator or LAC and the server side is called the L2TP Network Server or LNS.

Restricting L2TP to the IPsec tunnel

Warning
L2TP is insecure, and should not be accessible outside the IPsec connection

iptables

When using iptables, use the following rules to block all L2TP connection outside the ipsec layer:

root #iptables -t filter -A INPUT -p udp -m policy --dir in --pol ipsec -m udp --dport l2tp -j ACCEPT

root #iptables -t filter -A INPUT -p udp -m udp --dport l2tp -j REJECT --reject-with icmp-port-unreachable

root #iptables -t filter -A OUTPUT -p udp -m policy --dir out --pol ipsec -m udp --sport l2tp -j ACCEPT

root #iptables -t filter -A OUTPUT -p udp -m udp --sport l2tp -j REJECT --reject-with icmp-port-unreachable

nftables

When using nftables, use the following script to block all L2TP connection outside the ipsec layer:

CODE

#!/sbin/nft -f
 
table ip l2tp-ipsec {
        chain INPUT {
                type filter hook input priority filter; policy accept;
                meta ipsec exists udp dport 1701 counter accept
                udp dport 1701 counter reject
        }
 
	chain OUTPUT {
                type filter hook output priority filter; policy accept;
                rt ipsec exists udp sport 1701 counter accept
                udp sport 1701 counter reject
        }
}

firewalld

Firewalld only blocks incoming connection, not outgoing, and even «rich» rules are not expressive enough to state what is needed for inbound. However, firewalld is designed to live with nftables tables, so the nftables solution above will work and not interfere with it.

Using xl2tpd

Unlike other L2TP servers, xl2tpd can maintain an IP address pool without a DHCP or RADIUS server. This is a layering violation, but for a small setup it is extremely convenient:

FILE /etc/xl2tpd/xl2tpd.conf

[global]
port = 1701
access control = no
 
[lns default]
ip range = 172.21.118.2-172.21.118.254
local ip = 172.21.118.1
require authentication = yes
name = LinuxVPN
pppoptfile = /etc/ppp/options.xl2tpd

To use a RADIUS or DHCP server, leave off the ip range and local ip parts.

Create the options file as well:

FILE /etc/ppp/options.xl2tpd

This line is for Windows’s benefit. Without it, (at least as of Windows 10) Windows will send EAP probes, which pppd rejects, but Windows will insist, rather then fall back. Manual configuration of the VPN connection will be for Windows to use MSCHAPv2 instead of EAP. By limiting Windows’s choice, it will work «out of the box».

If more flexibility is desired and Windows client configuration is not an issue, this line can be dropped.

PPP

The final layer to configure is the Point-to-Point Protocol (PPP) layer. The package to install here is net-dialup/pppd.

root #emerge --ask net-dialup/pppd

Authentication

PPP is used to perform authentication. Unlike the certificate based or PSK authentication, the PPP layer is more for authenticating (and authorizing) the end users’ access to the VPN.

Authentication via chap.secrets

For small users (typically, those wanting to connect their home network from elsewhere), authentication can be done through the chap.secrets file:

FILE /etc/ppp/chap-secrets

# Secrets for authentication using CHAP
# client        server  secret                  IP addresses
avatar          *       unontainium              *

Note
When authenticating with domains, the client name will need to be mangled appropriately, in this case, EXAMPLE\\avatar.

Warning
/etc/ppp/chap-secrets contains unencrypted passwords, so make sure only root can read or write it

Authentication via Samba

When the machine is part of (or hosting) an MS Domain or AD forest, and the clients are using winbind, then Samba can do the authentication. Add plugin winbind.so to the ppp options. Setting up Samba and pppd to do this is beyond the scope of this document.

Authentication via RADIUS

pppd can use RADIUS. Ensure the radius USE flag is set on net-dialup/ppp. Then add plugin radius.so and plugin radattr.so to the PPP options. Setting up RADIUS is beyond the scope of this document.

Authentication via EAP-TLS

If individual users have certificates (which is not the same as the machine certificate above), then setup pppd to authenticate via EAP-TLS. Ensure the eap-tls USE flag is set on net-dialup/ppp. The require-eap option might need to be included in the PPP options file as well. Setting up pppd to do this is beyond the scope of this document.

Server Notes

Server behind NAT

When the server is behind NAT (Network Address Translation), which is usually the case when the server is hosted after a home router, some specific attention pointers can help in ensuring the IPsec connection is stable and working.

Opening ports

2 ports need to be open:

  • UDP port 500 (for ISAKMP)
  • UDP port 4500 (for NAT Traversal)

Make sure to forward those to the VPN server.

Also the following Internet Protocols (not ports) need to be allowed as well:

  • 50 (ESP)
  • 51 (AH)

This might need to be configured on the router side if the router has protocol specific settings (most don’t though).

Client Notes

General

Creating the PKCS12 file

The certificate should be packaged in a PKCS12 package. This can be done through openssl or gnutls:

user $openssl pkcs12 -export -certfile ca.crt -inkey client.example.com.key -in client.example.com.crt -out client.example.com.p12

user $certtool --load-ca-certificate /home/salahx/easy-rsa/pki/ca.crt --load-certificate /home/salahx/easy-rsa/pki/issued/client.example.com.crt --load-privkey /home/salahx/easy-rsa/pki/private/client.example.com.key --to-p12 --p12-name=client.example.com.crt --outder --outfile client.example.com.p12

Be sure to set a password. Some clients (like MacOS) will not open a passwordless p12 file. Some legacy clients can only handle DER encoded p12 files (default for openssl, certtool defaults to PEM). Also remember the certificate belongs to the machine/system, not the user.

Windows

RRAS Error 809: The network connection between your computer and VPN could not be established because the remote server is not responding…

When importing, it’s important to choose «Local Machine» to import to, NOT «Current User». Otherwise, Windows can’t find the certificate and just times out without ever contacting the IPSec server.

Weak proposals

Unlike other clients, Windows prefers the weakest proposal. So if 3des-sha1-modp1024 is offered, it will take it over a better option. On strongSwan, the added proposal aes128-sha1-modp1024 is added for the benefit of legacy clients (Windows 7 and earlier). Older version of Windows won’t offer anything stronger than modp1024 by default. It is possible to allow or force Windows to accept a better proposal through a registry hack. Set DWORD HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Rasman\Parameters\NegotiateDH2048_AES256 to 1 to enable Windows to accept aes256-sha1-modp2048, set it to 2 to not allow anything weaker.

If there are no legacy clients (see Android section below), and all Windows clients are at least Windows 10 21H2 (might work with earlier versions) OR have the above registry hack applies, and the server is running strongSwan, the proposal=aes128-sha1-modp1024 may be removed or adjusted.

Enabling split tunneling

By default, Windows connects via full tunnel mode (everything is routed over the VPN), however it’s possible to enable split tunnel in Windows.

Enable split tunneling via the GUI

Go to «Change adapter options» to show the adapters. Right-click the VPN connection, choose Properties, then Networking, then Internet Protocol Version 4 (TCP/IPv4), then Properties, then Advanced, then uncheck «Use default gateway on remote network».

Via PowerShell

CODE

Set-VPNconnection -name vpn.example.com -SplitTunneling $true

Substitute vpn.example.com with the given VPN connection name

Server behind NAT

Windows does not automatically support IPsec/L2TP servers behind NAT. See Configure a L2TP/IPsec server behind a NAT-T device to enable support.

RRAS Error 835: The L2TP connection attempt failed because the security layer could not authenticate the remote computer…

The subjectAltName of the server certificate MUST match the server name being connected to. (When connecting by IP address, Windows skips this check).

Mac OS X

MacOS X client require several steps:

  1. The CA and client certificates must be imported into the System keychain, not the Login keychain.
  2. In the Keychain app, the new CA is untrusted by default, so it must be marked trusted
  3. Also note that if corrected after the VPN connection is created, it is necessary to re-select the certificate under Authentication Settings to clear the error.

The «Account Name» should be the PPP username.

Note that Mac OS also checks the subjectAltName vs DNS, if it does not match, it will refuse to connect.

Android

As of Android 12, Android no longer supports IPsec/L2TP. Like Windows, Android won’t offer anything stronger than modp1024, so strongSwan config has an added proposal of aes128-sha1-modp1024. This works even on very old version of Android (at least 4.2). If there are no Android client or other legacy clients (see Windows above), the proposal=aes128-sha1-modp1024 may be removed or adjusted.

iOS

iOS does not support certificate-based authentication for IPSec/L2TP, only pre-shared keys (PSK). (It does support certificate for IPSec/XAuth, however).

External resources

  • Using a Linux L2TP/IPsec VPN server from Jacco de Leeuw

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • User logon name pre windows 2000
  • Wifi mouse pro windows
  • Windows 10 автозапуск до логина
  • Vag com 409 1 kkl usb драйвер windows 10
  • Куда сохраняются видео с камеры windows 10