Настройка Point-to-site VPN с помощью OpenVPN Remote Access Server на pfSense 2.3
Вводная информация
Point-to-Site VPN (Virtual Private Network) — технология, позволяющая организовать собственную виртуальную частную сеть и подключать к ней территориально удаленных пользователей. VPN представляет собой безопасный SSL/TLS-туннель между сервером и клиентами, предоставляет общий доступ в сетевым ресурсам, снижает расход интернет-трафика пользователей за счет использования сжатия, а также дает возможность маршрутизации всего клиентского трафика через VPN-сервер (аналогично прокси-серверу).
В данном руководстве мы рассмотрим процесс создания виртуальной частной сети с помощью свободной реализации технологии VPN — OpenVPN, поддерживаемой едва ли не всеми современными операционными системами (Windows, Mac OS, Linux, Android, iOS, ChromeOS). Настройка будет осуществляться на сервере, работающем под управлением pfSense 2.3.
Частное облако от 1cloud.ru
- Любые конфигурации виртуальных серверов
- Бесплатные частные сети
- Полная автоматизация управления
PfSense представляет собой дистрибутив на базе ОС FreeBSD, предназначенный для создания межсетевых экранов/маршрутизаторов. При весьма широких возможностях, он бесплатный, нуждается лишь в минимальных аппаратных ресурсах, и имеет предустановленный понятный web-интерфейс управления. Подробнее ознакомиться с возможностями pfSense можно здесь.
Для упрощения процесса настройки и дальнейшего администрирования сервера мы будем использовать OpenVPN Remote Access Server — программное решение, включающее в себя непосредственно OpenVPN-сервер, собственный веб-интерфейс управления, а также набор автоматически настраиваемого клиентского ПО для соединения с сервером. Единственное ограничение Remote Access Server — необходимость лицензирования. Бесплатная (базовая) лицензия рассчитана на обслуживание двух VPN-клиентов. При увеличении числа пользователей потребуется приобретение дополнительных лицензий. На момент написания статьи их стоимость составляет 9.60$ в год за каждого, начиная с третьего, клиента. Подробная информация о лицензировании Access Server находится здесь.
1. Создание сервера pfSense и настройка OpenVPN Remote Access Server
Для дальнейших манипуляций нам потребуется хост pfSense. Если Вы используете сервис 1cloud.ru, то для подготовки сервера достаточно выбрать соответствующий шаблон (pfSense 2.3) при создании сервера — через несколько минут он будет готов к работе. Если же Вы планируете использовать сторонний хостинг или собственный сервер, потребуется сперва установить и настроить pfSense.
Итак, сервер готов. Переходим в его веб-интерфейс управления.
Входим, используя учетные данные, указанные в панели управления 1cloud. Затем открываем вкладку VPN > OpenVPN > Wizards.
Откроется мастер настройки OpenVPN Remote Access Server. Выбираем тип сервера (Type of Server) – Local User Access.
На следующем этапе следует указать параметры сертификата создаваемого центра сертификации (CA), который в дальнейшем, будет заверять сертификаты клиентов:
- Descriptive name: MyCA (можно указать иное)
- Key length: 2048 bit
- Lifetime: 3650 (срок действия сертификата. Оставим по умолчанию)
- Country Code: RU
- State or Province: Saint Petersburg
- City: Saint Petersburg
- Organization: 1cloud (название компании, подтверждающей сертификаты пользователей)
- E-mail: support@1cloud.ru
Кликаем “Add new CA”.
Теперь необходимо указать параметры самого сертификата CA. Можно ничего не изменять, только указать Descriptive Name – например «MyCAcrt». Кликаем «Create new Certificate».
Далее нужно настроить OpenVPN-cервер:
- Interface: WAN (сетевой интерфейс сервера, подключенный к интернету)
- Protocol: UDP
- Local Port: 1194
- Description: myVPN (любое удобное название)
- Tunnel Network: 10.0.8.0/24
- Redirect Gateway: Включить (Отключите эту опцию, если Вы не хотите, чтобы весь интернет-трафик клиента перенаправлялся через VPN-сервер.)
- Local Network: Оставляем пустым (Если Вы хотите, чтобы локальная сеть, находящаяся за сервером pfSense, была доступна для удаленных клиентов VPN, укажите здесь адресное пространство этой сети.)
- Concurrent Connections: 2 (Если Вы приобрели дополнительную лицензию OpenVPN Remote Access Server, укажите число, соответствующее количеству приобретенных лицензий)
- Inter-Client Communications: Включить (Если Вы не хотите, чтобы VPN-клиенты видели друг друга, отключите эту опцию)
- DNS Server 1 (2 и т.д.): указать DNS-серверы хоста pfSense. (узнать их адреса можно в разделе System > General Setup > DNS Servers)
Остальные параметры можно оставить по умолчанию. Кликаем «Next».
Теперь указываем параметры Firewall. Включаем обе опции: разрешаем внешние подключения для клиентов и трафик внутри VPN-туннеля.
Настройка серверной части завершена.
Теперь нам нужно добавить пользователей, которые в дальнейшем смогут подключаться к виртуальной частной сети. Для этого переходим в меню System > User Manager. Кликаем «Add» для добавления нового пользователя.
Вводим информацию о пользователе. Не забудьте активировать опцию “Click to create a user certificate” и указать созданный ранее центр сертификации в параметрах сертификата пользователя.
Аналогичным образом, при необходимости, добавляем второго (третьего и т.д.) пользователя.
2. Экспорт клиентских конфигураций и подключение пользователей
Для упрощения процедур конфигурации программ-клиентов, в pfSense предусмотрен дополнительный инструмент – “OpenVPN Client Export Utility”. Этот инструмент автоматически подготавливает установочные пакеты и конфигурационные файлы пользователей, что позволяет избежать ручной настройки VPN-клиента со стороны конечного пользователя.
Установим вышеописанный пакет. Для этого переходим в меню System > Package Manager > Available Packages. Находим в списке openvpn-client-export utility. Кликаем «Install» для его установки.
Сообщение со скриншота ниже говорит об успешном завершении установки.
Теперь можно экспортировать конфигурации на пользовательские устройства. Переходим во вкладку VPN > OpenVPN > Client Export.
Изменять какие-либо параметры, указанные на открывшейся странице, обычно нет необходимости.
В нижней части страницы находим поле «OpenVPN Clients». Здесь размещены версии конфигураций под различные типы клиентов.
Рассмотрим процесс подключения клиента к созданной виртуальной частной сети на самом распространенном примере – подключении ПК под управлением Windows.
- Для настройки Windows-клиента скачиваем соответствующий параметрам компьютера установочный пакет из списка (см. скриншот выше). Запускаем. Начинается инсталляция утилиты. Кликаем «Далее» (изменять стандартные параметры установки нет необходимости).
- Открываем установленный “OpenVPN GUI”. В трее появляется соответствующая иконка. При клике на нее, происходит подключение к VPN. В процессе подключения будет запрошено имя пользователя, указанное Вами при его создании в панели управления pfSense. При успешном соединении с сетью иконка OpenVPN в трее станет зеленой и отобразится уведомление о получении адреса в пространстве 10.0.8.0/24.
Если Вы включили опцию перенаправления всего клиентского трафика через сервер OpenVPN, то имеет смысл проверить корректность ее работы. Для этого в браузере проверяем IP-адрес клиентского устройства, например через myip.ru. Он должен совпадать с IP-адресом VPN сервера.
На этом настройка Point-to-site VPN завершена.
P.S. В рамках данной инструкции мы не будем описывать настройку клиентов на других ОС. Эту информацию можно найти непосредственно в разделе VPN > OpenVPN > Client Export > Client Install Packages.
Приведем только пример настройки VPN-клиента на ОС Ubuntu/Debian без установленного графического окружения (что зачастую актуально для серверов).
Войдите в терминал (непосредственно на настраиваемом устройстве или через SSH)
Последовательно введите следующие команды (каждая новая строка является отдельной командой):
sudo -s
apt-get update && apt-get upgrade
apt-get install openvpn
cp /home/user/openvpnfiles/* /etc/openvpn (копирование файлов конфигурации openvpn в рабочую директорию программы. Эта команда подразумевает, что файлы уже находятся в папке /home/user/openvpnfiles, и кроме них в ней ничего нет.)
/etc/init.d/openvpn restart
ifconfig
В результате выполнения последней команды, в окне терминала должен появиться список сетевых подключений, включающий в себя соедение TUN-это и есть подключенный VPN-туннель.
OpenVPNВ¶
OpenVPN is an open source SSL VPN solution that can be used for remote access clients and site-to-site connectivity. OpenVPN supports clients on a wide range of operating systems including all the BSDs, Linux, Android, Mac OS X, iOS, Solaris, Windows 2000 and newer, and even some VoIP handsets.
Every OpenVPN connection, whether remote access or site-to-site, consists of a server and a client. In the case of site-to-site VPNs, one firewall acts as the server and the other as the client. It does not matter which firewall possesses these roles. Typically the location of the primary firewall will provide server connectivity for all remote locations, whose firewalls are configured as clients. This is functionally equivalent to the opposite configuration the primary location configured as a client connecting to servers running on the firewalls at the remote locations. In practice, the servers are nearly always run on a central location.
There are several types of authentication methods that can be used with OpenVPN: shared key, X.509 (also known as SSL/TLS or PKI), user authentication via local, LDAP, and RADIUS, or a combination of X.509 and user authentication. For shared key, a single key is generated that will be used on both sides. SSL/TLS involves using a trusted set of certificates and keys. User authentication can be configured with or without SSL/TLS, but its use is preferable where possible due to the increased security is offers.
The settings for an OpenVPN instance are covered in this chapter as well as a run-through of the OpenVPN Remote Access Server wizard, client configurations, and examples of multiple site-to-site connection scenarios.
While OpenVPN is an SSL VPN, it is not a “clientless” SSL VPN in the sense that commercial firewall vendors commonly state. The OpenVPN client must be installed on all client devices. In reality no VPN solution is truly “clientless”, and this terminology is nothing more than a marketing ploy. For more in depth discussion on SSL VPNs, this post from Matthew Grooms, an IPsec tools and pfSense® developer, in the mailing list archives provides some excellent information.
For general discussion of the various types of VPNs available in pfSense and their pros and cons, see Virtual Private Networks .
pfSense Hangouts on Youtube to view the September 2014 Hangout on Advanced OpenVPN Concepts and the September 2015 Hangout on Remote Access VPNs
OpenVPN and CertificatesВ¶
Using certificates is the preferred means of running remote access VPNs, because it allows access to be revoked for individual machines. With shared keys, either a unique server and port for must be created for each client, or the same key must be distributed to all clients. The former gets to be a management nightmare, and the latter is problematic in the case of a compromised key. If a client machine is compromised, stolen, or lost, or otherwise needs revoked, the shared key must be re-issued to all clients. With a PKI deployment, if a client is compromised, or access needs to be revoked for any other reason, simply revoke that client’s certificate. No other clients are affected.
The pfSense GUI includes a certificate management interface that is fully integrated with OpenVPN. Certificate authorities (CAs) and server certificates are managed in the Certificate Manager in the web interface, located at System > Cert Manager. User certificates are also managed in the web interface, as a part of the built-in user manager found at System > User Manager. Certificates may be generated for any user account created locally on the firewall except for the default admin account. For further information on creating a certificate authority, certificates, and certificate revocation lists, see Certificate Management .
InQuize / pfSense as an OpenVPN client.md
pfSense as an OpenVPN client for specific devices
One of the most powerful features of pfSense is it’s ability to direct your data requests through different end-points using NAT rules. pfSense is amazing as an OpenVPN client because it can selectively route any device on the network through the VPN service (i.e., my tablets and TV go through US servers, while my smartphone, VoIP, computers go my local ISP).
This setup becomes extremely handy for use with applications which are not aware of OpenVPN protocol, eg. download managers, torrent clients, etc. Expecting privacy you should be positive that traffic won’t go through your ISP’s gateway in case of failure on side of VPN provider. And obviously OpenVPN client should automatically reconnect as soon as service goes live again.
Note: This How-To is meant for pfSense 2.1.x. For those using 2.2 Beta, there is a bug that prevents this from working. Read about here in the pfSense forum thread, “cannot NAT trough OPT1 interface on multiwan”. The bug has been filed in redmine and at the time of this writing, it has been fixed for IPv4 traffic.
Note: By the time of editing, in 2.2.4-RELEASE version of pfSense the only way to route traffic through OpenVPN client seems to be «redirect-gateway def1» advanced option, which redirects absolutely all traffic and pfSense default gateway becomes the same thing with OpenVPN client’s gateway and not the ISP’s one. There is a way to still route traffic to ISP avoiding VPN tunnel. Basically, in such case pfSense becomes an OpenVPN client for it’s whole LAN subnet. This fact makes it clunky to use this guide on a main router because for each firewall rule you need to change default gateway to the right one. This why I use a separate pfSense virtual machine on a Proxmox server to provide VPN access for specific virtual machines using dedicated virtual subnet. Needles to say that I could also assign a physical interface for such purpose for use on some physical machines.
- Go to System > Cert Manager
- In the CAs tab, click the + icon to add a new Certificate Authority
- Fill in a Descriptive name like “[VPN PROVIDER] CA”
- Copy and paste Certificate data . It can be found in one of two .crt files, provided by VPN service. In some cases .ovpn file may include Certificate Authority information between . tags. Do not include this tags. All certificates going into pfSense should have similar format:
- Click Save .
- Go to the Certificates tab and click the + icon to add your VPN certificate and private key.
- Fill in a Descriptive name like “[VPN PROVIDER] CERT”
- Copy and paste Certificate data . It can be found in one of two .crt files, provided by VPN service. In some cases .ovpn file may include Certificate information between . tags. Do not include this tags.
- Copy and paste Private key data . It can be found in .key file, provided by VPN service. In some cases .ovpn file may include private key information between . tags. Do not include this tags. All private keys going into pfSense should have similar format:
- Click Save
Configure OpenVPN client:
- Go to VPN > OpenVPN
- Click the Client tab.
- Click the + icon to add a new client.
Note: Most of the settings on this tab totally depend on VPN provider.
These are important for the how-to:
- Interface set to WAN interface.
- Server host name resolution needs to be checked in order for client to automatically reconnect.
- Peer Certificate Authority and Client Certificate set to previosly defined.
- redirect-gateway def1 should persist in Advanced options to actually route traffic through VPN. These are the rest for my VPN provider:
- Server Mode = Peer to Peer ( SSL/TLS )
- Protocol = UDP => Server port = 1194
- Protocol = TCP => Server port = 443
- Device mode = tap
- Description = «[VPN Provider name]»
- TLS Authentication : unchecked Enable authentication of TLS packets
Note: if your VPN provider uses TLS Authentication you should check it, uncheck Automatically generate a shared TLS authentication key. and paste your shared key. It usually can be found in .ovpn configuration file between . tags. Do not include this tags. Paste should look like this:
- Encryption algorithm = BF-CBC (128-bit)
- Auth Digest Algorithm = RSA-SHA1 (160-bit)
- Hardware Crypto = BSD cryptodev engine — RSA, DSA, DH (Depends on CPU)
- Compression = Enabled with Adaptive Compression
- Advanced = ns-cert-type server;redirect-gateway def1;persist-key;persist-tun;mute 20;explicit-exit-notify
- Verbosity level = 4
- Click Save
Validate connection status:
- Go to Status > System Logs
- Select the OpenVPN tab.
- Verify that you have successfully connected. Specifically look for Initialization Sequence Completed statement. It may be anywhere between other log entries but should be tagged with time when you clicked Save on client configuration tab. If you don’t see it, it means you are not connected. Check your configuration again. Use the log to look for errors. These are probably flags in your advance options or encryption settings. Double check that you pasted right certificates and keys.
####Configure OpenVPN gateway interface:
- Go to Interfaces > (assign)
- In Available network ports: select ovpnc# [VPN Provider name] according to the Description given on client configuration step.
- Click the + icon and add a new interface. It will be called OPT#
- Click the OPT# name of new interface to configure it.
- Change the name of OPT# into something more useful, eg. name of VPN server.
- IPv4 Configuration Type = None
- IPv6 Configuration Type = None
- You may want to decide on Block private networks for your setup. Mine is unchecked since this pfSense is a virtual machine in a private network.
- Click Save
Verify working gateways:
- Go to Status > Dashboard
- Look for [VPN Provider name] entry in Interfaces table (Alternatively Status > Interfaces )
- Verify that you have an IP Address for your VPN.
- If no, try going to Status > Services and restarting OpenVPN service by clicking the play button next to OpenVPN client: [VPN Provider name]
Note: you may want to have OpenVPN table on dashboard to see client connection status. Click + icon right under Status: Dashboard header at the top of page, select OpenVPN and click Save Settings button.
- Go to System > Routing
- Verify that your gateways are available: there should be green play icon before [VPN Provider name]_VPNV4
Note: In pfSense 2.1.x or below that entry should have IP address Gateway column. If no , try opening the entry, scrolling down and clicking Save . That seemed to restart it. Note: In pfSense 2.2-Beta or above there probably would be dynamic in Gateway column of VPN entry.
- Go to Firewall > NAT
- Select the Outbound tab.
- Note rules in automatically generated table.
- Select the Manual Outbound NAT Rule Generation (AON — Advanced Outboud NAT) radio button.
- Click Save
- Now you should see all the same rules ungrouped and editable. Verify presence of all seing earlier rules.
- By clicking + icon next to the rule entry, copy every rule changing only the interface to the one you created for VPN client [VPN Server name]
Note: rules for VPN interface should follow the corresponding for WAN interface. Order is crucial here. That is the reason we are not able to use «convinient» Hybrid Outbound NAT rule generation (Automatic Outbound NAT + rules below) . As it stated on the bottom of the page: «If hybrid outbound NAT is selected, mappings you specify on this page will be used, followed by the automatically generated ones.»
Note: Rule of thumb: final NAT mappings table should have 4 rules for each interface on the system except OpenVPN client’s one (eg. 4x WAN + 4x LAN) (Theoretically, you may configure more then one OpenVPN client on single pfSense, but since “redirect-gateway def1” option redirects all the traffic, I don’t believe in success of such setups).
From this moment you use Firewall rules to direct traffic from your IPs/networks/interfaces to either WAN gateway (for direct ISP connection) or VPN client gateway for VPN access. I especially do not define any steps for further configuration because some pfSense version behave little bit different here and everyone’s setup would be different, so you should play a bit with rules, learn how they affect your network and you will be rewarded eventually with pretty good skills and understanding of the whole picture.