OpenVPN в Windows

Материал из Xgu.ru

Перейти к: навигация, поиск
stub.png
Данная страница находится в разработке.
Эта страница ещё не закончена. Информация, представленная здесь, может оказаться неполной или неверной.

Если вы считаете, что её стоило бы доработать как можно быстрее, пожалуйста, скажите об этом.

Автор: Сергей Черепенин

Короткий URL: openvpn/windows


Содержание

[править] Организация соединения с использованием статических ключей

В данной главе рассматривается подготовка и организация vpn соединения с использованием статического ключа. В качестве сервера используется компьютер с операционной системой Debian GNU/Linux Etch на ядре 2.6.18-4-686, а в качестве клиента - Windows 2003 SP2.

Настройки сетевых интерфейсов сервера и клиента:

  • сервер
$ /sbin/ifconfig

eth0      Link encap:Ethernet  HWaddr 00:04:76:A1:EF:BB  
          inet addr:10.0.17.1  Bcast:10.255.255.255  Mask:255.0.0.0
          inet6 addr: fe80::204:76ff:fea1:efbb/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:5663951 errors:0 dropped:0 overruns:1 frame:0
          TX packets:2928925 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:1850432381 (1.7 GiB)  TX bytes:330532572 (315.2 MiB)
          Interrupt:169 

eth1      Link encap:Ethernet  HWaddr 00:60:08:20:7B:0B  
          inet addr:192.168.16.15  Bcast:192.168.16.255  Mask:255.255.255.0
          inet6 addr: fe80::260:8ff:fe20:7b0b/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:104476 errors:0 dropped:0 overruns:0 frame:0
          TX packets:120582 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:19294593 (18.4 MiB)  TX bytes:48250297 (46.0 MiB)
          Interrupt:185 Base address:0xc400 

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:64752 errors:0 dropped:0 overruns:0 frame:0
          TX packets:64752 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:43343011 (41.3 MiB)  TX bytes:43343011 (41.3 MiB)
  • клиент
C:\Documents and Settings\Administrator>ipconfig /all

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : net.nt
Description . . . . . . . . . . . : 3Com EtherLink XL 10/100 PCI For Complete
PC Management NIC (3C905C-TX)
Physical Address. . . . . . . . . : 00-04-75-75-46-C1
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
IP Address. . . . . . . . . . . . : 192.168.16.197
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.16.15
DHCP Server . . . . . . . . . . . : 192.168.16.15
DNS Servers . . . . . . . . . . . : 192.168.16.15
Lease Obtained. . . . . . . . . . : 12 июля 2011 г. 11:49:13
Lease Expires . . . . . . . . . . : 12 июля 2011 г. 11:59:13

Теперь необходимо проинсталлировать необходимое программное обеспечение принятым, для каждой операционной системы, способом.

На сервере под управлением ОС Debian GNU/Linux достаточно выполнить команду:

$ sudo apt-get install openvpn -y

Список файлов, входящих в состав пакета openvpn_2.0.9-4_i386.deb можно просмотреть с помощью команды:

$ sudo dpkg -L openvpn

Кроме этого, проверьте имеет ли Ваше ядро поддержку TUN/TAP устройств. Сделать это можно выполнив следующую команду:

$ grep CONFIG_TUN /boot/config-`uname -r`
CONFIG_TUN=m

Если Ваше ядро не поддерживает эти устройства:

$ grep CONFIG_TUN /boot/config-`uname -r`
# CONFIG_TUN is not set

то для продолжения Вам необходимо скомпилировать этот модуль.

На клиенте, под управлением ОС Windows 2003 SP2, необходимо в первую очередь получить инсталляционный файл. Скачать его можно с помощью ссылки. На момент написания статьи текущая версия OpenVPN - 2.0.9. Затем необходимо проинсталлировать полученное программное обеспечение обычным вызовом .exe файла. Во время инсталляции оставьте все значения по умолчанию.

После установки необходимо сгенерировать статический ключ на любом компьютере - сервере или клиенте, скопировать его на другой компьютер и отредактировать конфигурационные файлы сервера и клиента.

  • Для генерации статического ключа в ОС Debian необходимо выполнить следующую команду:
 
$ sudo openvpn --genkey --secret /etc/openvpn/static.key
  • Для генерации статического ключа в ОС Windows необходимо запустить следующую команду: Пуск -> Программы -> OpenVPN -> Generate a static OpenVPN key. В результате будет создан файл C:\Program Files\OpenVPN\config\key.txt. Затем необходимо скопировать этот ключ на другого участника соединения.

Далее отредактируйте конфигурационные файлы сервера и клиента:

  • конфигурационный файл сервера /etc/openvpn/sample.conf:
cat  /etc/openvpn/sample.conf 
dev tap
ifconfig 172.16.0.1 255.255.255.0
secret key.txt
comp-lzo
  • конфигурационный файл клиента C:\Program Files\OpenVPN\config\sample.ovpn:
remote 192.168.16.15
dev tap
ifconfig 172.16.0.2 255.255.255.0
secret key.txt
comp-lzo

Из указанных выше конфигурационных файлов видно, что различие серверного и клиентского конфигов очень мало, и сервером будет тот компьютер, у которого не указан параметр remote

Выполним команду на сервере:

sudo openvpn --config /etc/openvpn/sample.conf
Tue Jul  12 11:54:44 2011 OpenVPN 2.0.9 i486-pc-linux-gnu [SSL] [LZO] [EPOLL] built on Jan 21 2007
Tue Jul  12 11:54:44 2011 IMPORTANT: OpenVPN's default port number is now 1194, based on an official port number assignment by IANA.  OpenVPN 2.0-beta16 and earlier used 5000 as the default port.
Tue Jul  12 11:54:44 2011 WARNING: file 'key.txt' is group or others accessible
Tue Jul  12 11:54:44 2011 TUN/TAP device tap0 opened
Tue Jul  12 11:54:44 2011 /sbin/ifconfig tap0 172.16.0.1 netmask 255.255.255.0 mtu 1500 broadcast 172.16.0.255
Tue Jul  12 11:54:44 2011 UDPv4 link local (bound): [undef]:1194
Tue Jul  12 11:54:44 2011 UDPv4 link remote: [undef]
Tue Jul  12 11:54:57 2011 Peer Connection Initiated with 192.168.16.197:1194
Tue Jul  12 11:54:58 2011 Initialization Sequence Completed

Затем на windows:

Ovpn1.png

Запустить сервис OpenVPN под Windows можно и из cmd:

C:\Documents and Settings\Administrator>cd "c:\Program Files\OpenVPN\config"
C:\Program Files\OpenVPN\config>openvpn --config sample.ovpn
Tue Jul 12 12:52:24 2011 us=640078 Current Parameter Settings:
Tue Jul 12 12:52:24 2011 us=640364   config = 'sample.ovpn'
Tue Jul 12 12:52:24 2011 us=640535   mode = 0
Tue Jul 12 12:52:24 2011 us=640688   show_ciphers = DISABLED
Tue Jul 12 12:52:24 2011 us=640852   show_digests = DISABLED
Tue Jul 12 12:52:24 2011 us=641022   show_engines = DISABLED
Tue Jul 12 12:52:24 2011 us=641192   genkey = DISABLED
Tue Jul 12 12:52:24 2011 us=641358   key_pass_file = '[UNDEF]'
Tue Jul 12 12:52:24 2011 us=641529   show_tls_ciphers = DISABLED
Tue Jul 12 12:52:24 2011 us=641706   proto = 0
Tue Jul 12 12:52:24 2011 us=641863 NOTE: --mute triggered...
Tue Jul 112 12:52:24 2011 us=642076 178 variation(s) on previous 10 message(s) su
ppressed by --mute
Tue Jul 12 12:52:24 2011 us=642346 OpenVPN 2.0.9 Win32-MinGW [SSL] [LZO] built o
n Oct  1 2006
Tue Jul 12 12:52:24 2011 us=643308 IMPORTANT: OpenVPN's default port number is n
ow 1194, based on an official port number assignment by IANA.  OpenVPN 2.0-beta1
6 and earlier used 5000 as the default port.
Tue Jul 12 12:52:24 2011 us=643684 WARNING: --ping should normally be used with
--ping-restart or --ping-exit
Tue Jul 12 12:52:24 2011 us=644588 Static Encrypt: Cipher 'BF-CBC' initialized w
ith 128 bit key
Tue Jul 12 12:52:24 2011 us=644902 Static Encrypt: Using 160 bit message hash 'S
HA1' for HMAC authentication
Tue Jul 12 12:52:24 2011 us=645257 Static Decrypt: Cipher 'BF-CBC' initialized w
ith 128 bit key
Tue Jul 12 12:52:24 2011 us=645528 Static Decrypt: Using 160 bit message hash 'S
HA1' for HMAC authentication
Tue Jul 12 12:52:24 2011 us=645839 LZO compression initialized
Tue Jul 12 12:52:24 2011 us=650456 TAP-WIN32 device [Local Area Connection 2] op
ened: \\.\Global\{59380ED2-2769-41B0-97F6-C4BC571471CA}.tap
Tue Jul 12 12:52:24 2011 us=650817 TAP-Win32 Driver Version 8.4
Tue Jul 12 12:52:24 2011 us=651030 TAP-Win32 MTU=1500
Tue Jul 12 12:52:24 2011 us=651244 Notified TAP-Win32 driver to set a DHCP IP/ne
tmask of 172.16.0.2/255.255.255.0 on interface {59380ED2-2769-41B0-97F6-C4BC5714
71CA} [DHCP-serv: 172.16.0.0, lease-time: 31536000]
Tue Jul 12 12:52:24 2011 us=687896 Successful ARP Flush on interface [65540] {59
380ED2-2769-41B0-97F6-C4BC571471CA}
Tue Jul 12 12:52:24 2011 us=694501 Data Channel MTU parms [ L:1577 D:1450 EF:45
EB:135 ET:32 EL:0 AF:3/1 ]
Tue Jul 12 12:52:24 2011 us=698395 Local Options String: 'V4,dev-type tap,link-m
tu 1577,tun-mtu 1532,proto UDPv4,ifconfig 172.16.0.0 255.255.255.0,comp-lzo,ciph
er BF-CBC,auth SHA1,keysize 128,secret'
Tue Jul 12 12:52:24 2011 us=704162 Expected Remote Options String: 'V4,dev-type
tap,link-mtu 1577,tun-mtu 1532,proto UDPv4,ifconfig 172.16.0.0 255.255.255.0,com
p-lzo,cipher BF-CBC,auth SHA1,keysize 128,secret'
Tue Jul 12 12:52:24 2011 us=710006 Local Options hash (VER=V4): '94889dd0'
Tue Jul 12 12:52:24 2011 us=712199 Expected Remote Options hash (VER=V4): '94889
dd0'
Tue Jul 12 12:52:24 2011 us=716063 Socket Buffers: R=[8192->8192] S=[8192->8192]
Tue Jul 12 12:52:24 2011 us=720016 UDPv4 link local (bound): [undef]:1194
Tue Jul 12 12:52:24 2011 us=722180 UDPv4 link remote: 192.168.16.15:1194
Tue Jul 12 12:52:30 2011 us=303168 Peer Connection Initiated with 192.168.16.15:
1194
Tue Jul 12 12:52:31 2011 us=54350 TEST ROUTES: 0/0 succeeded len=-1 ret=1 a=0 u/
d=up
Tue Jul 12 12:52:31 2011 us=58342 Initialization Sequence Completed

Теперь проверьте состояние интерфейсов при помощи команды /sbin/ifconfig на сервере:

/sbin/ifconfig 
eth0      Link encap:Ethernet  HWaddr 00:04:76:A1:EF:BB  
          inet addr:10.0.17.1  Bcast:10.255.255.255  Mask:255.0.0.0
          inet6 addr: fe80::204:76ff:fea1:efbb/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:5663951 errors:0 dropped:0 overruns:1 frame:0
          TX packets:2928925 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:1850432381 (1.7 GiB)  TX bytes:330532572 (315.2 MiB)
          Interrupt:169 

eth1      Link encap:Ethernet  HWaddr 00:60:08:20:7B:0B  
          inet addr:192.168.16.15  Bcast:192.168.16.255  Mask:255.255.255.0
          inet6 addr: fe80::260:8ff:fe20:7b0b/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:104476 errors:0 dropped:0 overruns:0 frame:0
          TX packets:120582 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:19294593 (18.4 MiB)  TX bytes:48250297 (46.0 MiB)
          Interrupt:185 Base address:0xc400 

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:64752 errors:0 dropped:0 overruns:0 frame:0
          TX packets:64752 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:43343011 (41.3 MiB)  TX bytes:43343011 (41.3 MiB)

tap0      Link encap:Ethernet  HWaddr 86:FA:EC:53:C3:84  
          inet addr:172.16.0.1  Bcast:172.16.0.255  Mask:255.255.255.0
          inet6 addr: fe80::84fa:ecff:fe53:c384/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:83 errors:0 dropped:0 overruns:0 frame:0
          TX packets:63 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100 
          RX bytes:10893 (10.6 KiB)  TX bytes:9344 (9.1 KiB)

И на windows-клиенте при помощи команды ipconfig /all:

C:\Documents and Settings\Administrator>ipconfig /all

Windows IP Configuration

Host Name . . . . . . . . . . . . : win0
Primary Dns Suffix  . . . . . . . :
Node Type . . . . . . . . . . . . : Unknown
IP Routing Enabled. . . . . . . . : No
WINS Proxy Enabled. . . . . . . . : No
DNS Suffix Search List. . . . . . : net.nt
Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : net.nt
Description . . . . . . . . . . . : 3Com EtherLink XL 10/100 PCI For Complete
PC Management NIC (3C905C-TX)
Physical Address. . . . . . . . . : 00-04-75-75-46-C1
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
IP Address. . . . . . . . . . . . : 192.168.16.197
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.16.15
DHCP Server . . . . . . . . . . . : 192.168.16.15
DNS Servers . . . . . . . . . . . : 192.168.16.15
Lease Obtained. . . . . . . . . . : 12 июля 2011 г. 12:14:14
Lease Expires . . . . . . . . . . : 12 июля 2011 г. 12:24:14

Ethernet adapter Local Area Connection 2:
Connection-specific DNS Suffix  . :
Description . . . . . . . . . . . : TAP-Win32 Adapter V8
Physical Address. . . . . . . . . : 00-FF-59-38-0E-D2
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
IP Address. . . . . . . . . . . . : 172.16.0.2
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . :
DHCP Server . . . . . . . . . . . : 172.16.0.0
Lease Obtained. . . . . . . . . . : 12 июля 2011 г. 12:15:23
Lease Expires . . . . . . . . . . : 12 июля 2011 г. 12:15:23

И проверьте только что установленный туннель :

ping 172.16.0.2 -c 4
PING 172.16.0.2 (172.16.0.2) 56(84) bytes of data.
64 bytes from 172.16.0.2: icmp_seq=1 ttl=128 time=4.57 ms
64 bytes from 172.16.0.2: icmp_seq=2 ttl=128 time=0.813 ms
64 bytes from 172.16.0.2: icmp_seq=3 ttl=128 time=0.950 ms
64 bytes from 172.16.0.2: icmp_seq=4 ttl=128 time=1.11 ms

--- 172.16.0.2 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3002ms
rtt min/avg/max/mdev = 0.813/1.863/4.578/1.571 ms

На этом организация vpn соединения с использованием статических ключей завершена.

[править] Создание сертификатов на Windows с использованием easy-rsa

В первую очередь необходимо создать каталог c:\Progam Files\OpenVPN\easy-rsa\keys и скопировать в него файлы serial.start и index.txt.start без суффикса .start. Сделать это можно при помощи следующей команды запущенной в cmd:

C:\Documents and Settings\Administrator>cd "c:\Program Files\OpenVPN\easy-rsa" && mkdir keys && copy serial.start keys\serial && copy index.txt.start keys\index.txt
        1 file(s) copied.
        1 file(s) copied.

Затем необходимо скопировать файлы vars.bat.sample и openssl.cnf.sample в vars.bat и openssl.cnf соответственно. Сделать это можно, выполнив batch файл C:\Program Files\OpenVPN\easy-rsa\init-config.bat при помощи следующей команды:

C:\Documents and Settings\Administrator>cd "c:\Program Files\OpenVPN\easy-rsa" && init-config.bat
C:\Program Files\OpenVPN\easy-rsa>copy vars.bat.sample vars.bat
        1 file(s) copied.
C:\Program Files\OpenVPN\easy-rsa>copy openssl.cnf.sample openssl.cnf
        1 file(s) copied.

Файл openssl.cnf --- >>>>
Файл vars.bat ----->>>

Затем необходимо отредактировать файл vars.bat:

@echo off
set HOME=%ProgramFiles%\OpenVPN\easy-rsa\
set KEY_CONFIG=openssl.cnf
set KEY_DIR=keys
set KEY_SIZE=1024
set KEY_COUNTRY=UA
set KEY_PROVINCE=Kiev
set KEY_CITY=Kiev
set KEY_ORG=TechExpert
set KEY_EMAIL=otradnyi@mail.ru

Затем необходимо внести изменения в среду окружения согласно файла vars.bat. Сделать это можно из cmd при помощи следующей команды:

C:\Documents and Settings\Administrator>cd "c:\Program Files\OpenVPN\easy-rsa" && vars.bat
  • Затем необходимо создать Diffie-Hellman key:
C:\Program Files\OpenVPN\easy-rsa>vars.bat
C:\Program Files\OpenVPN\easy-rsa>build-dh.bat
Loading 'screen' into random state - done
Generating DH parameters, 1024 bit long safe prime, generator 2
This is going to take a long time
..................+...............................................................................+..........+.......................
.....+.....+.............+........................................................+.........+........................................
+.........+...................................................................................+......................................
.................................................................+...................................................+...............
.........+............................................................................+........+............................+........
....................+........................................+.........+............................+................................
.......................+...........+.................................................................+..........+....................
............................................+......+.........................+.......................+.....................+.........
........................................................+....+.......................................................................
.............................+..........................................+............................................................
..................................+...........+....................................................+.................................
.............................................................+......................................+.............................+..
.................................................................................................................+...................
.....++*++*++*

В результате в каталоге C:\Program Files\OpenVPN\easy-rsa\keys появится файл dh1024.pem:

C:\Program Files\OpenVPN\easy-rsa>dir keys
Volume in drive C has no label.
Volume Serial Number is 508A-A105
Directory of C:\Program Files\OpenVPN\easy-rsa\keys
13.07.2011  13:22    <DIR>          .
13.07.2011  13:22    <DIR>          ..
13.07.2011  13:22               245 dh1024.pem
13.07.2011  13:06                 0 index.txt
13.07.2011  13:06                 3 serial
               3 File(s)            248 bytes
               2 Dir(s)   7 517 777 920 bytes free
  • Теперь необходимо создать Certificate Authority. Создается он путем выполнения файла build-ca.bat:
C:\Program Files\OpenVPN\easy-rsa>vars.bat



C:\Program Files\OpenVPN\easy-rsa>build-ca.bat
Loading 'screen' into random state - done
Generating a 1024 bit RSA private key
.......++++++
...................++++++
writing new private key to 'keys\ca.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [UA]:UA
State or Province Name (full name) [Kiev]:Kiev
Locality Name (eg, city) [Kiev]:Kiev
Organization Name (eg, company) [TechExpert]:TechExpert
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:win0
Email Address [otradnyi@mail.ru]:otradnyi@mail.ru

В результате выполнения этой команды в каталоге keys было создано два файла ca.crt и ca.key:

C:\Program Files\OpenVPN\easy-rsa>dir keys
Volume in drive C has no label.
Volume Serial Number is 508A-A105
Directory of C:\Program Files\OpenVPN\easy-rsa\keys
13.07.2011  13:38    <DIR>          .
13.07.2011  13:38    <DIR>          ..
13.07.2011  13:38             1 224 ca.crt
13.07.2011  13:38               887 ca.key
13.07.2011  13:22               245 dh1024.pem
13.07.2011  13:06                 0 index.txt
13.07.2011  13:06                 3 serial
               5 File(s)          2 359 bytes
               2 Dir(s)   7 517 769 728 bytes free

ca.crt --->>>
ca.key ---->>>

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

Для этого необходимо выполнить файл build-key-server.bat с параметром имени сервера, в нашем случае это win0:

C:\Program Files\OpenVPN\easy-rsa>vars.bat
C:\Program Files\OpenVPN\easy-rsa>build-key-server.bat win0
Loading 'screen' into random state - done
Generating a 1024 bit RSA private key
............................................++++++
....................++++++
writing new private key to 'keys\win0.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [UA]:
State or Province Name (full name) [Kiev]:
Locality Name (eg, city) [Kiev]:
Organization Name (eg, company) [TechExpert]:
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:win0
Email Address [otradnyi@mail.ru]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from openssl.cnf
Loading 'screen' into random state - done
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'UA'
stateOrProvinceName   :PRINTABLE:'Kiev'
localityName          :PRINTABLE:'Kiev'
organizationName      :PRINTABLE:'TechExpert'
organizationalUnitName:PRINTABLE:'IT'
commonName            :PRINTABLE:'win0'
emailAddress          :IA5STRING:'otradnyi@mail.ru'
Certificate is to be certified until Jul  13 11:25:57 2017 GMT (3650 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

В результате в каталоге:

C:\Program Files\OpenVPN\easy-rsa>dir keys
Volume in drive C has no label.
Volume Serial Number is 508A-A105
Directory of C:\Program Files\OpenVPN\easy-rsa\keys
13.07.2011  14:26    <DIR>          .
13.07.2011  14:26    <DIR>          ..
13.07.2011  14:26             3 629 01.pem
13.07.2011  13:38             1 224 ca.crt
13.07.2011  13:38               887 ca.key
13.07.2011  13:22               245 dh1024.pem
13.07.2011  14:26                99 index.txt
13.07.2011  14:26                21 index.txt.attr
13.07.2011  14:26                 3 serial
13.07.2011  14:26             3 629 win0.crt
13.07.2011  14:25               680 win0.csr
13.07.2011  14:25               887 win0.key
               10 File(s)         11 304 bytes
               2 Dir(s)   7 517 663 232 bytes free
  • Теперь создадим ключ клиента:
C:\Program Files\OpenVPN\easy-rsa>build-key.bat roman
Loading 'screen' into random state - done
Generating a 1024 bit RSA private key
........++++++
........++++++
writing new private key to 'keys\roman.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [UA]:
State or Province Name (full name) [Kiev]:
Locality Name (eg, city) [Kiev]:
Organization Name (eg, company) [TechExpert]:
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:roman
Email Address [otradnyi@mail.ru]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from openssl.cnf
Loading 'screen' into random state - done
DEBUG[load_index]: unique_subject = "yes"
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'UA'
stateOrProvinceName   :PRINTABLE:'Kiev'
localityName          :PRINTABLE:'Kiev'
organizationName      :PRINTABLE:'TechExpert'
organizationalUnitName:PRINTABLE:'IT'
commonName            :PRINTABLE:'roman'
emailAddress          :IA5STRING:'otradnyi@mail.ru'
Certificate is to be certified until Jul  13 11:37:01 2017 GMT (3650 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

В результате в каталоге:

C:\Program Files\OpenVPN\easy-rsa>dir keys
Volume in drive C has no label.
Volume Serial Number is 508A-A105
Directory of C:\Program Files\OpenVPN\easy-rsa\keys
13.07.2011  14:37    <DIR>          .
13.07.2011  14:37    <DIR>          ..
13.07.2011  14:26             3 629 01.pem
13.07.2011  14:37             3 531 02.pem
13.07.2011  13:38             1 224 ca.crt
13.07.2011  13:38               887 ca.key
13.07.2011  13:22               245 dh1024.pem
13.07.2011  14:37               199 index.txt
13.07.2011  14:37                21 index.txt.attr
13.07.2011  14:37                 3 serial
13.07.2011  14:37             3 531 roman.crt
13.07.2011  14:37               680 roman.csr
13.07.2011  14:37               887 roman.key
13.07.2011  14:26             3 629 win0.crt
13.07.2011  14:25               680 win0.csr
13.07.2011  14:25               887 win0.key
              14 File(s)         20 033 bytes
               2 Dir(s)   7 517 650 944 bytes free
  • Теперь необходимо скопировать roman.crt, roman.key и ca.crt в каталог /etc/openvpn.
  • mkdir /etc/openvpn/keys
  • Теперь необходимо поправить конфиги:

--Винда:

###remote 192.168.16.15
###secret key.txt

dev tap

ifconfig 172.16.0.2 255.255.255.0

###comp-lzo
tls-server
dh keys/dh1024.pem
ca keys/ca.crt
cert keys/win0.crt
key keys/win0.key

-- Linux

remote 192.168.16.197
dev tap
tls-client
ifconfig 172.168.0.1 255.255.255.0
dh dh1024.pem
ca ca.crt
cert roman.crt
key roman.key

Если при старте сервера на Windows возникнет ошибка:

system library:fopen:No such file or directory

Необходимо переместить каталог c:\Progam Files\OpenVPN\easy-rsa\keys в с:\keys и после этого модифицировать конфиг:

dev tap
ifconfig 172.16.0.2 255.255.255.0
tls-server
dh c:\\keys\\dh1024.pem
ca c:\\keys\\ca.crt
cert c:\\keys\\win0.crt
key c:\\keys\\win0.key

Теперь запустим сервер vpn из cmd под Windows с помощью следующей команды:

C:\Documents and Settings\Administrator>openvpn --config "c:\Program Files\OpenVPN\config\sample.ovpn"
Tue Jul 12 17:02:23 2011 us=612115 Current Parameter Settings:
Tue Jul 12 17:02:23 2011 us=612409   config = 'c:\Program Files\OpenVPN\config\sample.ovpn'
Tue Jul 12 17:02:23 2011 us=612634   mode = 0
Tue Jul 12 17:02:23 2011 us=612791   show_ciphers = DISABLED
Tue Jul 12 17:02:23 2011 us=612953   show_digests = DISABLED
Tue Jul 12 17:02:23 2011 us=613112   show_engines = DISABLED
Tue Jul 12 17:02:23 2011 us=613270   genkey = DISABLED
Tue Jul 12 17:02:23 2011 us=613427   key_pass_file = '[UNDEF]'
Tue Jul 12 17:02:23 2011 us=613591   show_tls_ciphers = DISABLED
Tue Jul 12 17:02:23 2011 us=613753   proto = 0
Tue Jul 12 17:02:23 2011 us=613910 NOTE: --mute triggered...
Tue Jul 12 17:02:23 2011 us=614111 178 variation(s) on previous 10 message(s) suppressed by --mute
Tue Jul 12 17:02:23 2011 us=614331 OpenVPN 2.0.9 Win32-MinGW [SSL] [LZO] built on Oct  1 2006
Tue Jul 12 17:02:23 2011 us=615260 IMPORTANT: OpenVPN's default port number is now 1194, based on an official port number assignment
.  OpenVPN 2.0-beta16 and earlier used 5000 as the default port.
Tue Jul 12 17:02:23 2011 us=615596 WARNING: --ping should normally be used with --ping-restart or --ping-exit
Tue Jul 12 17:02:23 2011 us=671943 Diffie-Hellman initialized with 1024 bit key
Tue Jul 12 17:02:23 2011 us=675391 Control Channel MTU parms [ L:1573 D:138 EF:38 EB:0 ET:0 EL:0 ]
Tue Jul 12 17:02:23 2011 us=680475 TAP-WIN32 device [Local Area Connection 4] opened: \\.\Global\{DDA59CFF-B7AE-4F0E-91DA-C111AF5139B
Tue Jul 12 17:02:23 2011 us=680823 TAP-Win32 Driver Version 8.4
Tue Jul 12 17:02:23 2011 us=681026 TAP-Win32 MTU=1500
Tue Jul 12 17:02:23 2011 us=681234 Notified TAP-Win32 driver to set a DHCP IP/netmask of 172.16.0.2/255.255.255.0 on interface {DDA59
E-4F0E-91DA-C111AF5139B5} [DHCP-serv: 172.16.0.0, lease-time: 31536000]
Tue Jul 12 17:02:23 2011 us=716919 Successful ARP Flush on interface [196612] {DDA59CFF-B7AE-4F0E-91DA-C111AF5139B5}
Tue Jul 12 17:02:23 2011 us=725976 Data Channel MTU parms [ L:1573 D:1450 EF:41 EB:4 ET:32 EL:0 ]
Tue Jul 12 17:02:23 2011 us=726302 Local Options String: 'V4,dev-type tap,link-mtu 1573,tun-mtu 1532,proto UDPv4,ifconfig 172.16.0.0
.255.0,cipher BF-CBC,auth SHA1,keysize 128,key-method 2,tls-server'
Tue Jul 12 17:02:23 2011 us=726626 Expected Remote Options String: 'V4,dev-type tap,link-mtu 1573,tun-mtu 1532,proto UDPv4,ifconfig 1
.0 255.255.255.0,cipher BF-CBC,auth SHA1,keysize 128,key-method 2,tls-client'
Tue Jul 12 17:02:23 2011 us=726987 Local Options hash (VER=V4): '79e31c21'
Tue Jul 12 17:02:23 2011 us=727192 Expected Remote Options hash (VER=V4): '5a258ee1'
Tue Jul 12 17:02:23 2011 us=727475 Socket Buffers: R=[8192->8192] S=[8192->8192]
Tue Jul 12 17:02:23 2011 us=727723 UDPv4 link local (bound): [undef]:1194
Tue Jul 12 17:02:23 2011 us=727898 UDPv4 link remote: [undef]

Затем на клиенте дадим команду:

sudo openvpn --config /etc/openvpn/sample.conf

И смотрим на продолжение вывода на сервере:

Tue Jul 12 17:05:23 2011 us=993139 TLS: Initial packet from 192.168.16.15:1194, sid=76cd5180 622a0d09
Tue Jul 12 17:05:24 2011 us=505011 VERIFY OK: depth=1, /C=UA/ST=Kiev/L=Kiev/O=TechExpert/OU=IT/CN=win0/emailAddress=otradnyi@mail.ru
Tue Jul 12 17:05:24 2011 us=506441 VERIFY OK: depth=0, /C=UA/ST=Kiev/O=TechExpert/OU=IT/CN=roman/emailAddress=otradnyi@mail.ru
Tue Jul 12 17:05:24 2011 us=567168 Data Channel Encrypt: Cipher 'BF-CBC' initialized with 128 bit key
Tue Jul 12 17:05:24 2011 us=567435 Data Channel Encrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
Tue Jul 12 17:05:24 2011 us=567739 Data Channel Decrypt: Cipher 'BF-CBC' initialized with 128 bit key
Tue Jul 12 17:05:24 2011 us=567977 Data Channel Decrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
Tue Jul 12 17:05:24 2011 us=569802 Control Channel: TLSv1, cipher TLSv1/SSLv3 DHE-RSA-AES256-SHA, 1024 bit RSA
Tue Jul 12 17:05:24 2011 us=570075 [roman] Peer Connection Initiated with 192.168.16.15:1194
Tue Jul 12 17:05:26 2011 us=153485 TEST ROUTES: 0/0 succeeded len=-1 ret=1 a=0 u/d=up
Tue Jul 12 17:05:26 2011 us=153796 Initialization Sequence Completed

И проверяем

ping 172.16.0.2 -c 4
PING 172.16.0.2 (172.16.0.2) 56(84) bytes of data.
64 bytes from 172.16.0.2: icmp_seq=1 ttl=128 time=8.91 ms
64 bytes from 172.16.0.2: icmp_seq=2 ttl=128 time=1.00 ms
64 bytes from 172.16.0.2: icmp_seq=3 ttl=128 time=1.23 ms
64 bytes from 172.16.0.2: icmp_seq=4 ttl=128 time=1.34 ms

[править] Создание сертификатов на Debian с использованием easy-rsa

ls -l /usr/share/doc/openvpn/examples/easy-rsa/
итого 80
drwxr-xr-x 2 root root 4096 2011-07-13 00:18 2.0
-rwxr-xr-x 1 root root  242 2011-07-13 13:06 build-ca
-rwxr-xr-x 1 root root  228 2011-07-13 13:06 build-dh
-rwxr-xr-x 1 root root  529 2011-07-13 13:06 build-inter
-rwxr-xr-x 1 root root  516 2011-07-13 13:06 build-key
-rwxr-xr-x 1 root root  424 2011-07-13 13:06 build-key-pass
-rwxr-xr-x 1 root root  695 2011-07-13 13:06 build-key-pkcs12
-rwxr-xr-x 1 root root  662 2011-07-13 13:06 build-key-server
-rwxr-xr-x 1 root root  466 2011-07-13 13:06 build-req
-rwxr-xr-x 1 root root  402 2011-07-13 13:06 build-req-pass
-rwxr-xr-x 1 root root  280 2011-07-13 13:06 clean-all
-rw-r--r-- 1 root root  264 2011-07-13 13:06 list-crl
-rw-r--r-- 1 root root  268 2011-07-13 13:06 make-crl
-rw-r--r-- 1 root root 7487 2011-07-13 13:06 openssl.cnf
-rw-r--r-- 1 root root 2619 2011-07-13 13:06 README.gz
-rw-r--r-- 1 root root  268 2011-07-13 13:06 revoke-crt
-rwxr-xr-x 1 root root  593 2011-07-13 13:06 revoke-full
-rwxr-xr-x 1 root root  411 2011-07-13 13:06 sign-req
-rw-r--r-- 1 root root 1266 2011-07-13 13:06 vars
sudo mkdir /usr/share/doc/openvpn/examples/easy-rsa/keys


sudo touch /usr/share/doc/openvpn/examples/easy-rsa/keys/index.txt
sudo touch /usr/share/doc/openvpn/examples/easy-rsa/keys/serial
sudo sh -c "echo 01 > /usr/share/doc/openvpn/examples/easy-rsa/keys/serial"


egrep -v '^\ *$|^#' vars

export D=`pwd`
export KEY_CONFIG=$D/openssl.cnf
export KEY_DIR=$D/keys
echo NOTE: when you run ./clean-all, I will be doing a rm -rf on $KEY_DIR
export KEY_SIZE=1024
export KEY_COUNTRY=UA
export KEY_PROVINCE=Kiev
export KEY_CITY=Kiev
export KEY_ORG="TechExpert"
export KEY_EMAIL="otradnyi@mail.ru"


# . vars

NOTE: when you run ./clean-all, I will be doing a rm -rf on /usr/share/doc/openvpn/examples/easy-rsa/keys
# echo $KEY_
$KEY_CITY      $KEY_COUNTRY   $KEY_EMAIL     $KEY_PROVINCE
$KEY_CONFIG    $KEY_DIR       $KEY_ORG       $KEY_SIZE

# echo $KEY_CITY
Kiev

# echo $KEY_CONFIG
/usr/share/doc/openvpn/examples/easy-rsa/openssl.cnf
# ./build-dh
Generating DH parameters, 1024 bit long safe prime, generator 2
This is going to take a long time
..................................................+.+.............
..................................................................
........................................+..+......................
............+........+............................................
........+.........................................+...............
...............................................+..................
..................................................................
..................................................................
..........................+.......................................
...................................................+..............
....+.......................................................+.....
.......................................+...........+..............
....+........+....................................................
..................+........+...............+......................
..................+...............................................
........................................................+.......+.
...................................+..........+....+..........+...
...............+..................................+...............
.........................................................+........
....................+...++*++*++*
# ./build-ca
Generating a 1024 bit RSA private key
.....................................................++++++
..........++++++
writing new private key to 'ca.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [UA]:
State or Province Name (full name) [Kiev]:
Locality Name (eg, city) [Kiev]:
Organization Name (eg, company) [TechExpert]:
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:roman
Email Address [otradnyi@mail.ru]:
# ls keys/
ca.crt  ca.key  dh1024.pem  index.txt  serial


# ./build-key-server roman
Generating a 1024 bit RSA private key
.............++++++
........++++++
writing new private key to 'roman.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [UA]:
State or Province Name (full name) [Kiev]:
Locality Name (eg, city) [Kiev]:
Organization Name (eg, company) [TechExpert]:
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:roman
Email Address [otradnyi@mail.ru]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /usr/share/doc/openvpn/examples/easy-rsa/openssl.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'UA'
stateOrProvinceName   :PRINTABLE:'Kiev'
localityName          :PRINTABLE:'Kiev'
organizationName      :PRINTABLE:'TechExpert'
organizationalUnitName:PRINTABLE:'IT'
commonName            :PRINTABLE:'roman'
emailAddress          :IA5STRING:'otradnyi@mail.ru'
Certificate is to be certified until Jul  13 09:00:09 2017 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
# ls keys/
01.pem  ca.crt  ca.key  dh1024.pem  index.txt  index.txt.attr  index.txt.old  serial  serial.old  roman.crt  roman.csr  roman.key
# ./build-key student
Generating a 1024 bit RSA private key
.++++++
....................++++++
writing new private key to 'student.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [UA]:
State or Province Name (full name) [Kiev]:
Locality Name (eg, city) [Kiev]:
Organization Name (eg, company) [TechExpert]:
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:student
Email Address [otradnyi@mail.ru]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /usr/share/doc/openvpn/examples/easy-rsa/openssl.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'UA'
stateOrProvinceName   :PRINTABLE:'Kiev'
localityName          :PRINTABLE:'Kiev'
organizationName      :PRINTABLE:'TechExpert'
organizationalUnitName:PRINTABLE:'IT'
commonName            :PRINTABLE:'student'
emailAddress          :IA5STRING:'otradnyi@mail.ru'
Certificate is to be certified until Jul  13 10:06:23 2017 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
cp keys/student1.crt ; keys/student1.key ; keys/ca.crt и keys/dh1024.pem на Windows

Конфиг сервера:

# cat /etc/openvpn/student1.conf
dev tap
ifconfig 172.16.0.1 255.255.255.0
tls-server
dh keys/dh1024.pem
ca keys/ca.crt
cert keys/roman.crt
key  keys/roman.key

Конфиг клиента:

dev tap
tls-client
dh c:\\keys\\dh1024.pem
ca c:\\keys\\ca.crt
cert c:\\keys\\student.crt
key c:\\keys\\student.key
ifconfig 172.16.0.2 255.255.255.0

Запуск openvpn на сервере:

# openvpn --config /etc/openvpn/student1.conf
Wed Jul  13 13:11:59 2011 OpenVPN 2.0.9 i486-pc-linux-gnu [SSL] [LZO] [EPOLL] built on Jan 21 2007
Wed Jul  13 13:11:59 2011 IMPORTANT: OpenVPN's default port number is now 1194, based on an official port number assignment by IANA.  OpenVPN 2.0-beta16 and earlier used 5000 as the default port.
Wed Jul  13 13:12:00 2011 TUN/TAP device tap0 opened
Wed Jul  13 13:12:00 2011 /sbin/ifconfig tap0 172.16.0.1 netmask 255.255.255.0 mtu 1500 broadcast 172.16.0.255
Wed Jul  13 13:12:00 2011 UDPv4 link local (bound): [undef]:1194
Wed Jul  13 13:12:00 2011 UDPv4 link remote: [undef]

Запуск на Windows клиенте из cmd:

C:\Documents and Settings\Administrator>openvpn --config "c:\Program Files\OpenV
PN\config\client.ovpn"

Проверка:

# ping 172.16.0.2 -c 4
PING 172.16.0.2 (172.16.0.2) 56(84) bytes of data.
64 bytes from 172.16.0.2: icmp_seq=1 ttl=128 time=3.72 ms
64 bytes from 172.16.0.2: icmp_seq=2 ttl=128 time=1.35 ms
64 bytes from 172.16.0.2: icmp_seq=3 ttl=128 time=1.44 ms
64 bytes from 172.16.0.2: icmp_seq=4 ttl=128 time=1.49 ms

--- 172.16.0.2 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3052ms
rtt min/avg/max/mdev = 1.353/2.004/3.727/0.996 ms

# ifconfig tap0
tap0      Link encap:Ethernet  HWaddr 42:FC:5B:E3:33:D2
          inet addr:172.16.0.1  Bcast:172.16.0.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:42 errors:0 dropped:0 overruns:0 frame:0
          TX packets:11 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:6199 (6.0 KiB)  TX bytes:902 (902.0 b)

[править] Настройка пула адресов для получения их клиентами

Для этого необходимо использовать tun устройство или с использованием tap устройства необходимо будет прописывать для каждого клиента адрес и маску:

  • на сервере:
# cat /etc/openvpn/student1.conf
dev tap
ifconfig 172.16.0.1 255.255.0.0.
ifconfig-pool 172.16.0.2 172.16.0.253 255.255.0.0
mode server
tls-server
dh keys/dh1024.pem
ca keys/ca.crt
cert keys/serzh.crt
key  keys/serzh.key
plugin /usr/lib/openvpn/openvpn-auth-pam.so login
  • на клиенте:
pull
auth-user-pass 
dev tap
remote 10.0.17.1
tls-client
dh c:\\keys\\dh1024.pem
ca c:\\keys\\ca.crt
cert c:\\keys\\student1.crt
key c:\\keys\\student1.key

[править] Настройка парольной аутентификации системных пользователей для установки подключения

Для этого необходимо в файле /etc/openvpn/student1.conf дописать следующие строки:

plugin /usr/lib/openvpn/openvpn-auth-pam.so login

А в клиентском конфиге:

pull
auth-user-pass

[править] Настройка OpenVPN для работы в качестве сервера

  • Во-первых, необходимо создать конфигурационный файл сервера. Его можно скопировать из каталога /usr/share/doc/openvpn/examples/sample-config-files/ и затем распаковать:
gzip -cd /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz \
>> /etc/openvpn/server.conf
  • Затем необходимо отредактировать этот файл:
# egrep -v '^\ *$|^#|;' /etc/openvpn/server.conf 

port 1194
proto tcp-server
dev tap
ca keys/ca.crt
cert keys/serzh.crt
key keys/serzh.key  
dh keys/dh1024.pem
ifconfig-pool-persist ipp.txt
ifconfig 172.16.0.1 255.255.255.0
server-bridge 172.16.0.1 255.255.255.0 172.16.0.2 172.16.0.253
client-config-dir ccd
client-to-client
keepalive 10 120
persist-key
persist-tun
status openvpn-status.log 3500
verb 3
plugin /usr/lib/openvpn/openvpn-auth-pam.so login
  • port 1194 - порт для прослушивания демоном openvpn


  • proto tcp-server - указание протокола соединения. Если опция не указана, то используется протокол не гарантированной доставки udp. Для tcp соединения необходимо указать онду из опций tcp-server или tcp-client для сервера и клиента соответственно. Демон, запущенный с опцией tcp-server ожидает входящие соединения. Демон, запущенный с опцией tcp-client, будет инициировать соединение и в случае неудачи будет производить повторные попытки подключения через каждые 5 секунд (определяется connect-retry опцией, 5 секунд - значение по умолчанию).


  • dev tap

. . .

  • ca keys/ca.crt - Опция ca определяет корневой (root) сертификат, которым подписаны клиентские пары сертификат/ключ. Значение этой опции keys/ca.crt указывает месторасположение этого сертификата относительно каталога /etc/openvpn. (Или, иными словами, это открытый ключ сервера)


  • cert keys/serzh.crt - Каждый участник OpenVPN соединения в TLS режиме должен иметь собственный сертификат и файл с закрытым ключом. Каждый сертификат должен быть подписан закрытым ключом центра сертификатов, чей открытый ключ указывается в опции ca.


  • key keys/serzh.key - Закрытый ключ, который генерируется вместе с сертификатом, указанным в опции cert


  • dh keys/dh1024.pem - Файл, содержащий параметры Diffie Hellman

. . .

  • ifconfig-pool-persist ipp.txt - Файл ассоциаций client <-> virtual IP.

Например:

# cat ipp.txt 
student1,172.16.0.2
natali,172.16.0.5

где первое поле - имя используемого с TLS режиме сертификата.

  • ifconfig 172.16.0.1 255.255.255.0 - IP-адрес, присваиваемый серверу на устройстве /dev/tap


  • server-bridge 172.16.0.1 255.255.255.0 172.16.0.2 172.16.0.253 - Использование сервера в режиме моста. Это дает возможность видеть клиетам не только сервер но и других клиентов (при указании опции client-to-client).


  • client-config-dir ccd - Опция определяет каталог в /etc/openvpn/ с конфигурационными файлами клиентов. В этих файлах могут быть переопределены опции основного конфигурационного файла для каждого из клиентов.


  • keepalive 10 120



  • persist-key - Не перечитывать заново файлы ключей при получении сигнала SIGUSR1 (переустановка соединения) или через интервал, указанный опцией ping-restart n (переустановить соединение через n секунд после отправки последнего icmp пакета клиенту, который остался без ответа)


  • persist-tun - Не закрывать или переоткрывать устройства TUN/TAP при получении сигнала SIGUSR1 или по прошествию интервала n опции ping-restart n.


  • status openvpn-status.log 3500 - В файл /etc/openvpn/openvpn-status.log будет записываться статус активных подключений каждые 5 минут


  • verb 3 - Уровень вывода отладочной информации.


  • plugin /usr/lib/openvpn/openvpn-auth-pam.so login - Подключение модуля аутентификации openvpn-auth-pam.so и использование программы login для аутентификации пользователей во время установки соединения.



Конфигурационный файл клиента:

pull
auth-user-pass 
dev tap
proto tcp-client
remote 10.0.17.1
tls-client
dh c:\\keys\\dh1024.pem
ca c:\\keys\\ca.crt
cert c:\\keys\\student1.crt
key c:\\keys\\student1.key

[править] Openvpn FreeBSD

Инсталляция:

$ cd /usr/ports/security/openvpn

$ sudo make install clean
___________________________________
 Options for openvpn 2.0.6_4  
[X] PW_SAVE  Interactive passwords may be read from a file   
___________________________________

Настройка:

$ sudo mkdir /usr/local/etc/openvpn

$ sudo openvpn --genkey --secret /usr/local/etc/openvpn/static.key

$ sudo sh -c 'cat << CONF >> /usr/local/etc/openvpn/sample.conf
dev tun
ifconfig 172.16.0.1 172.16.0.2
secret /usr/local/etc/openvpn/static.key
comp-lzo
CONF'

Копируем на Windows static.key в C:\Program Files\OpenVPN\static.key

Затем создаем конфигурационный файл клиента openvpn - C:\Program Files\OpenVPN\config на Windows:

remote 192.168.15.238
dev tun
ifconfig 172.16.0.2 172.16.0.1
secret "C:\\Program Files\\OpenVPN\\config\\static.key"
comp-lzo

Запускаем на сервере FreeBSD openvpn:

$ sudo openvpn --config /usr/local/etc/openvpn/sample.conf
Wed Aug 29 19:42:16 2007 OpenVPN 2.0.6 i386-portbld-freebsd6.2 [SSL] [LZO] built on Aug 29 2007
Wed Aug 29 19:42:16 2007 IMPORTANT: OpenVPN's default port number is now 1194, based on an official port number assignment by IANA.  OpenVPN 2.0-beta16 and earlier used 5000 as the default port.
Wed Aug 29 19:42:16 2007 LZO compression initialized
Wed Aug 29 19:42:16 2007 TUN/TAP device /dev/tun0 opened
Wed Aug 29 19:42:16 2007 /sbin/ifconfig tun0 172.16.0.1 172.16.0.2 mtu 1500 netmask 255.255.255.255 up
Wed Aug 29 19:42:16 2007 UDPv4 link local (bound): [undef]:1194
Wed Aug 29 19:42:16 2007 UDPv4 link remote: [undef]
.
.
.

И подключаемся с Windows клиентом:

C:\Documents and Settings\Administrator>openvpn --config "C:\Program Files\OpenV
PN\config\sample.ovpn"
Wed Aug 29 19:44:50 2007 OpenVPN 2.0.9 Win32-MinGW [SSL] [LZO] built on Oct  1 2
006
Wed Aug 29 19:44:50 2007 IMPORTANT: OpenVPN's default port number is now 1194, b
ased on an official port number assignment by IANA.  OpenVPN 2.0-beta16 and earl
ier used 5000 as the default port.
Wed Aug 29 19:44:50 2007 LZO compression initialized
Wed Aug 29 19:44:50 2007 TAP-WIN32 device [??????????? ?? ????????? ???? 3] open
ed: \\.\Global\{338C1B96-AA76-4B7F-8E7F-489452A64B06}.tap
Wed Aug 29 19:44:50 2007 Notified TAP-Win32 driver to set a DHCP IP/netmask of 1
72.16.0.2/255.255.255.252 on interface {338C1B96-AA76-4B7F-8E7F-489452A64B06} [D
HCP-serv: 172.16.0.1, lease-time: 31536000]
Wed Aug 29 19:44:50 2007 Successful ARP Flush on interface [131076] {338C1B96-AA
76-4B7F-8E7F-489452A64B06}
Wed Aug 29 19:44:50 2007 UDPv4 link local (bound): [undef]:1194
Wed Aug 29 19:44:50 2007 UDPv4 link remote: 192.168.15.238:1194
Wed Aug 29 19:45:01 2007 Peer Connection Initiated with 192.168.15.238:1194
Wed Aug 29 19:45:02 2007 Initialization Sequence Completed

И проверяем:

C:\Documents and Settings\Administrator>ping 172.16.0.1

Pinging 172.16.0.1 with 32 bytes of data:

Reply from 172.16.0.1: bytes=32 time=1ms TTL=64
Reply from 172.16.0.1: bytes=32 time<1ms TTL=64
Reply from 172.16.0.1: bytes=32 time<1ms TTL=64
Reply from 172.16.0.1: bytes=32 time<1ms TTL=64

Ping statistics for 172.16.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 1ms, Average = 0ms

[править] Дополнительная информация

[править] Материалы по OpenVPN на xgu.ru