Это старая версия документа.
Содержание
OpenVPN
Если вы хотите больше, чем просто предварительно распространенные ключи, OpenVPN упрощает установку и использование инфраструктуры открытых ключей (PKI), предназначенной для аутентификации с использованием SSL/TLS сертификатов и обмена ключами между VPN сервером и клиентами. OpenVPN может использоваться режимах VPN с роутингом и сетевым мостом и настраиваться на использование как UDP так и TCP. Номер порта также может настраиваться, но официально используется 1194. И он один используется для всех коммуникаций. Реализации VPN клиента доступны почти для всего, включая все дистрибутивы Linux, OS X, Windows и OpenWRT, являющийся основой для WLAN роутеров.
Установка сервера
Для установки openvpn наберите в терминале:
sudo apt-get install openvpn
Установка структуры открытых ключей (PKI)
Первым шагом при построении конфигурации OpenVPN является установка PKI. PKI состоит из:
отдельные сертификаты (также известные как открытые ключи) и секретные ключи для сервера и каждого клиента
главный сертификат центра сертификатов (CA) и секретный ключ, которые используются для цифровой подписи сертификатов сервера и клиентов.
OpenVPN поддерживает двустороннюю аутентификацию на основе сертификатов, означающую что клиент должен аутентифицировать серверный сертификат, а сервер должен аутентифицировать клиентский прежде чем будет установлено взаимное доверие.
И сервер и клиент аутентифицируют друг друга сначала проверяя, что представленный сертификат подписан главным сертификатом центра сертификатов, а затем проверяя информацию в заголовке свеже-аутентифицированного сертификата, такую как общее имя или тип сертификата (клиент или сервер).
Установка центра сертификатов
Для установки вашего собственного центра сертификатов (CA) и генерации сертификатов с секретными ключами для OpenVPN сервера и множества клиентов, сперва скопируйте easy-rsa каталог в /etc/openvpn. Это гарантирует, что любые изменения в сценариях не будут потеряны при обновлении пакета. Из терминала переключитесь на суперпользователя (sudo -s - прим. пер.) и выполните:
mkdir /etc/openvpn/easy-rsa/ cp -r /usr/share/doc/openvpn/examples/easy-rsa/2.0/* /etc/openvpn/easy-rsa/
Далее отредактируйте /etc/openvpn/easy-rsa/vars, исправив следующее в соответствии с вашей действительностью:
export KEY_COUNTRY="US" export KEY_PROVINCE="NC" export KEY_CITY="Winston-Salem" export KEY_ORG="Example Company" export KEY_EMAIL="steve@example.com"
Введите следующее для создания главного сертификата центра сертификатов и его секретного ключа:
cd /etc/openvpn/easy-rsa/ source vars ./clean-all ./build-ca
Серверные сертификаты
Далее мы создадим сертификат и секретный ключ для сервера:
./build-key-server myservername
Как и на предыдущем шаге большинство параметров можно выбирать по умолчанию. Два других запроса требуют положительного ответа: "Sign the certificate? [y/n]" и "1 out of 1 certificate requests certified, commit? [y/n]".
Должны быть созданы параметры Деффи-Хеллмана (Diffie-Hellman) для OpenVPN сервера:
./build-dh
Все сертификаты и ключи будут создаваться в подкаталоге keys/. Общая практика копировать их в /etc/openvpn/:
cd keys/ cp myservername.crt myservername.key ca.crt dh1024.pem /etc/openvpn/
Клиентские сертификаты
VPN клиент тоже требует наличие сертификата для аутентификации на сервере. Обычно вы создаете отдельные сертификаты для каждого клиента. Для создания сертификата, введите следующее в терминале под суперпользователем:
cd /etc/openvpn/easy-rsa/ source vars ./build-key client1
Скопируйте следующие файлы на сторону клиента, используя защищенный метод:
/etc/openvpn/ca.crt
/etc/openvpn/easy-rsa/keys/client1.crt
/etc/openvpn/easy-rsa/keys/client1.key
Поскольку сертификаты и секретные ключи требуются только на стороне клиента, вам нужно удалить их с сервера.
Настройка простого сервера
Вместе с вашей установкой OpenVPN вы получаете эти примеры конфигурационных файлов (и много чего еще, если проверите):
root@server:/# ls -l /usr/share/doc/openvpn/examples/sample-config-files/ total 68 -rw-r--r-- 1 root root 3427 2011-07-04 15:09 client.conf -rw-r--r-- 1 root root 4141 2011-07-04 15:09 server.conf.gz
Начните с копирования и распаковки server.conf.gz в /etc/openvpn/server.conf:
sudo cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /etc/openvpn/ sudo gzip -d /etc/openvpn/server.conf.gz
Отредактируйте /etc/openvpn/server.conf и убедитесь что следующие строки указывают на сертификаты и ключи, которые мы создали в предыдущем разделе.
ca ca.crt cert myservername.crt key myservername.key dh dh1024.pem
Это тот минимум, который вы должны настроить, чтобы получить работающий OpenVPN сервер. Вы можете использовать все значения по умолчанию из файла примера server.conf. Теперь запустите сервер. Вы найдете журнал событий и ошибок в вашем syslog.
root@server:/etc/openvpn# /etc/init.d/openvpn start * Starting virtual private network daemon(s)... * Autostarting VPN 'server' [ OK ]
Теперь проверьте, что OpenVPN создал интерфейс tun0:
root@server:/etc/openvpn# ifconfig tun0 tun0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 inet addr:10.8.0.1 P-t-P:10.8.0.2 Mask:255.255.255.255 UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1 [...]
Настройка простого клиента
Существует несколько реализаций клиента OpenVPN как с графическим интерфейсом так и без него. Вы можете сможете прочитать больше о клиентах в следующем разделе. На данный момент мы используем OpenVPN клиент для Ubuntu который использует ту же программу, что и сервер. Поэтому вам снова придется поставить пакет openvpn но уже на клиентской машине:
sudo apt-get install openvpn
Тем временем скопируем файл примера client.conf в каталог /etc/openvpn/:
sudo cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf /etc/openvpn/
Скопируйте ключи клиента и сертификат центра сертификатов, созданные в предыдущем разделе, например, в /etc/openvpn/ и отредактируйте /etc/openvpn/client.conf, чтобы убедиться, что следующие строки указывают на эти файлы. Если вы положили файлы в /etc/openvpn/, то путь к ним можете опустить.
ca ca.crt cert client1.crt key client1.key
И вам осталось указать адрес или имя OpenVPN сервера. Убедитесь в наличии ключевого слова client в файле настроек. Оно включает режим клиента:
client remote vpnserver.example.com 1194
Далее запустим OpenVPN клиента:
root@client:/etc/openvpn# /etc/init.d/openvpn start * Starting virtual private network daemon(s)... * Autostarting VPN 'client' [ OK ]
Убедитесь, что интерфейс tun0 создан:
root@client:/etc/openvpn# ifconfig tun0 tun0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 inet addr:10.8.0.6 P-t-P:10.8.0.5 Mask:255.255.255.255 UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1
Проверьте, что вам доступен OpenVPN сервер:
root@client:/etc/openvpn# ping 10.8.0.1 PING 10.8.0.1 (10.8.0.1) 56(84) bytes of data. 64 bytes from 10.8.0.1: icmp_req=1 ttl=64 time=0.920 ms
Сервер OpenVPN всегда использует первый доступный адрес в сети клиента и только этот IP адрес будет откликаться на ping. Например, если вы настроили маску /24 клиентской сети, то будет использован адрес, оканчивающийся на .1. Адрес P-t-P, который вы видите в выводе ifconfig выше обычно не отвечает на запросы ping.
Проверьте вашу маршрутизацию:
root@client:/etc/openvpn# netstat -rn Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface 10.8.0.5 0.0.0.0 255.255.255.255 UH 0 0 0 tun0 10.8.0.1 10.8.0.5 255.255.255.255 UGH 0 0 0 tun0 192.168.42.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 0.0.0.0 192.168.42.1 0.0.0.0 UG 0 0 0 eth0
Решение первичных проблем
If the above didn't work for you, check this:
Check your syslog, e.g. grep -i vpn /var/log/syslog
Can the client connect to the server machine? Maybe a firewall is blocking access? Check syslog on server.
Client and server must use same protocol and port, e.g. UDP port 1194, see port and proto config option
Client and server must use same config regarding compression, see comp-lzo config option
Client and server must use same config regarding bridged vs routed mode, see server vs server-bridge config option
Расширенные настройки
Расширенная конфигурация перенаправленного VPN на сервере
The above is a very simple working VPN. The client can access services on the VPN server machine through an encrypted tunnel. If you want to reach more servers or anything in other networks, push some routes to the clients. E.g. if your company's network can be summarized to the network 192.168.0.0/16, you could push this route to the clients. But you will also have to change the routing for the way back - your servers need to know a route to the VPN client-network.
Or you might push a default gateway to all the clients to send all their internet traffic to the VPN gateway first and from there via the company firewall into the internet. This section shows you some possible options.
Push routes to the client to allow it to reach other private subnets behind the server. Remember that these private subnets will also need to know to route the OpenVPN client address pool (10.8.0.0/24) back to the OpenVPN server.
push «route 10.0.0.0 255.0.0.0»
If enabled, this directive will configure all clients to redirect their default network gateway through the VPN, causing all IP traffic such as web browsing and and DNS lookups to go through the VPN (the OpenVPN server machine or your central firewall may need to NAT the TUN/TAP interface to the internet in order for this to work properly).
push «redirect-gateway def1 bypass-dhcp»
Configure server mode and supply a VPN subnet for OpenVPN to draw client addresses from. The server will take 10.8.0.1 for itself, the rest will be made available to clients. Each client will be able to reach the server on 10.8.0.1. Comment this line out if you are ethernet bridging.
server 10.8.0.0 255.255.255.0
Maintain a record of client to virtual IP address associations in this file. If OpenVPN goes down or is restarted, reconnecting clients can be assigned the same virtual IP address from the pool that was previously assigned.
ifconfig-pool-persist ipp.txt
Push DNS servers to the client.
push «dhcp-option DNS 10.0.0.2» push «dhcp-option DNS 10.1.0.2»
Allow client to client communication.
client-to-client
Enable compression on the VPN link.
comp-lzo
The keepalive directive causes ping-like messages to be sent back and forth over the link so that each side knows when the other side has gone down. Ping every 1 second, assume that remote peer is down if no ping received during a 3 second time period.
keepalive 1 3
It's a good idea to reduce the OpenVPN daemon's privileges after initialization.
user nobody group nogroup
OpenVPN 2.0 includes a feature that allows the OpenVPN server to securely obtain a username and password from a connecting client, and to use that information as a basis for authenticating the client. To use this authentication method, first add the auth-user-pass directive to the client configuration. It will direct the OpenVPN client to query the user for a username/password, passing it on to the server over the secure TLS channel.
# client config! auth-user-pass
This will tell the OpenVPN server to validate the username/password entered by clients using the login PAM module. Useful if you have centralized authentication with e.g. Kerberos.
plugin /usr/lib/openvpn/openvpn-auth-pam.so login
Please read the OpenVPN hardening security guide for further security advice.
Расширенная настройка VPN с мостом на сервере
OpenVPN can be setup for either a routed or a bridged VPN mode. Sometimes this is also referred to as OSI layer-2 versus layer-3 VPN. In a bridged VPN all layer-2 frames - e.g. all ethernet frames - are sent to the VPN partners and in a routed VPN only layer-3 packets are sent to VPN partners. In bridged mode all traffic including traffic which was traditionally LAN-local like local network broadcasts, DHCP requests, ARP requests etc. are sent to VPN partners whereas in routed mode this would be filtered.
Подготовка настроек интерфейса для сетевого моста на сервере
Make sure you have the bridge-utils package installed:
sudo apt-get install bridge-utils
Before you setup OpenVPN in bridged mode you need to change your interface configuration. Let's assume your server has an interface eth0 connected to the internet and an interface eth1 connected to the LAN you want to bridge. Your /etc/network/interfaces would like this:
auto eth0 iface eth0 inet static
address 1.2.3.4 netmask 255.255.255.248 default 1.2.3.1
auto eth1 iface eth1 inet static
address 10.0.0.4 netmask 255.255.255.0
This straight forward interface config needs to be changed into a bridged mode like where the config of interface eth1 moves to the new br0 interface. Plus we configure that br0 should bridge interface eth1. We also need to make sure that interface eth1 is always in promiscuous mode - this tells the interface to forward all ethernet frames to the IP stack.
auto eth0 iface eth0 inet static
address 1.2.3.4 netmask 255.255.255.248 default 1.2.3.1
auto eth1 iface eth1 inet manual
up ip link set $IFACE up promisc on
auto br0 iface br0 inet static
address 10.0.0.4 netmask 255.255.255.0 bridge_ports eth1
At this point you need to restart networking. Be prepared that this might not work as expected and that you will lose remote connectivity. Make sure you can solve problems having local access.
sudo /etc/init.d/network restart
Подготовка настроек сервера для сетевого моста
Edit /etc/openvpn/server.conf changing the following options to:
;dev tun dev tap up «/etc/openvpn/up.sh br0 eth1» ;server 10.8.0.0 255.255.255.0 server-bridge 10.0.0.4 255.255.255.0 10.0.0.128 10.0.0.254
Next, create a helper script to add the tap interface to the bridge and to ensure that eth1 is promiscuous mode. Create /etc/openvpn/up.sh:
#!/bin/sh
BR=$1 ETHDEV=$2 TAPDEV=$3
/sbin/ip link set «$TAPDEV» up /sbin/ip link set «$ETHDEV» promisc on /sbin/brctl addif $BR $TAPDEV
Then make it executable:
sudo chmod 755 /etc/openvpn/up.sh
After configuring the server, restart openvpn by entering:
sudo /etc/init.d/openvpn restart
Настройка клиента
First, install openvpn on the client:
sudo apt-get install openvpn
Then with the server configured and the client certificates copied to the /etc/openvpn/ directory, create a client configuration file by copying the example. In a terminal on the client machine enter:
sudo cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf /etc/openvpn
Now edit /etc/openvpn/client.conf changing the following options:
dev tap ;dev tun
Finally, restart openvpn:
sudo /etc/init.d/openvpn restart
You should now be able to connect to the remote LAN through the VPN.
Реализации клиентского программного обеспечения
Графический интерфейс сетевого менеджера Linux для OpenVPN
Many Linux distributions including Ubuntu desktop variants come with Network Manager, a nice GUI to configure your network settings. It also can manage your VPN connections. Make sure you have package network-manager-openvpn installed. Here you see that the installation installs all other required packages as well:
root@client:~# apt-get install network-manager-openvpn Reading package lists… Done Building dependency tree Reading state information… Done The following extra packages will be installed:
liblzo2-2 libpkcs11-helper1 network-manager-openvpn-gnome openvpn
Suggested packages:
resolvconf
The following NEW packages will be installed:
liblzo2-2 libpkcs11-helper1 network-manager-openvpn network-manager-openvpn-gnome openvpn
0 upgraded, 5 newly installed, 0 to remove and 631 not upgraded. Need to get 700 kB of archives. After this operation, 3,031 kB of additional disk space will be used. Do you want to continue [Y/n]?
To inform network-manager about the new installed packages you will have to restart it:
root@client:~# restart network-manager network-manager start/running, process 3078
Open the Network Manager GUI, select the VPN tab and then the 'Add' button. Select OpenVPN as the VPN type in the opening requester and press 'Create'. In the next window add the OpenVPN's server name as the 'Gateway', set 'Type' to 'Certificates (TLS)', point 'User Certificate' to your user certificate, 'CA Certificate' to your CA certificate and 'Private Key' to your private key file. Use the advanced button to enable compression or other special settings you set on the server. Now try to establish your VPN.
OpenVPN с графическим интерфейсом под Mac OS X: Tunnelblick
Tunnelblick is an excellent free, open source implementation of a GUI for OpenVPN for OS X. The project's homepage is at http://code.google.com/p/tunnelblick/. Download the latest OS X installer from there and install it. Then put your client.ovpn config file together with the certificates and keys in /Users/username/Library/Application Support/Tunnelblick/Configurations/ and lauch Tunnelblick from your Application folder.
# sample client.ovpn for Tunnelblick client remote blue.example.com port 1194 proto udp dev tun dev-type tun ns-cert-type server reneg-sec 86400 auth-user-pass auth-nocache auth-retry interact comp-lzo yes verb 3 ca ca.crt cert client.crt key client.key
OpenVPN с графическим интерфейсом под Windows 7
First download and install the latest OpenVPN Windows Installer. OpenVPN 2.2.1 was the latest when this was written. Additionally download an alternative Open VPN Windows GUI. The OpenVPN MI GUI from http://openvpn-mi-gui.inside-security.de seems to be a nice one for Windows 7. Download the latest version. 20110624 was the latest version when this was written.
You need to start the OpenVPN service. Goto Start > Computer > Manage > Services and Applications > Services. Find the OpenVPN service and start it. Set it's startup type to automatic. When you start the OpenVPN MI GUI the first time you need to run it as an administrator. You have to right click on it and you will see that option.
You will have to write your OpenVPN config in a textfile and place it in C:\Program Files\OpenVPN\config\client.ovpn along with the CA certificate. You could put the user certificate in the user's home directory like in the follwing example.
# C:\Program Files\OpenVPN\config\client.ovpn client remote server.example.com port 1194 proto udp dev tun dev-type tun ns-cert-type server reneg-sec 86400 auth-user-pass auth-retry interact comp-lzo yes verb 3 ca ca.crt cert «C:\\Users\\username\\My Documents\\openvpn\\client.crt» key «C:\\Users\\username\\My Documents\\openvpn\\client.key» management 127.0.0.1 1194 management-hold management-query-passwords auth-retry interact
OpenVPN для OpenWRT
OpenWRT is described as a Linux distribution for embedded devices like WLAN router. There are certain types of WLAN routers who can be flashed to run OpenWRT. Depending on the available memory on your OpenWRT router you can run software like OpenVPN and you could for example build a small inexpensive branch office router with VPN connectivity to the central office. More info on OpenVPN on OpenWRT is here. And here is the OpenWRT project's homepage: http://openwrt.org
Log into your OpenWRT router and install OpenVPN:
opkg update opkg install openvpn
Check out /etc/config/openvpn and put you client config in there. Copy certificated and keys to /etc/openvpn/
config openvpn client1
option enable 1 option client 1
# option dev tap
option dev tun option proto udp option ca /etc/openvpn/ca.crt option cert /etc/openvpn/client.crt option key /etc/openvpn/client.key option comp_lzo 1
Restart OpenVPN:
/etc/init.d/openvpn restart
You will have to see if you need to adjust your router's routing and firewall rules.