Настройка OpenVPN клиента

openvpn

Настройка OpenVPN клиента

Устанавливаем OpenVPN.

Создаем и переходим в папку с файлами конфигурации:

Copy
mkdir /usr/local/etc/openvpn && cd /usr/local/etc/openvpn

Копируем сертификат и ключи клиента: ca.crt, client.crt, client.key, ta.key. Ключи являются текстовыми файлами, если прямое копирование затруднено, можно использовать буфер обмена SSH-клиента.

Ограничиваем доступ к ключам:

Copy
chmod 600 client.key ta.key && chown root:wheel client.key ta.key

Копируем шаблон конфига клиента:

Copy
cp /usr/local/share/examples/openvpn/sample-config-files/client.conf /usr/local/etc/openvpn/

Редактируем файл конфигурации:

Copy
ee client.conf

Конфигурация клиента client.conf:

|```

Sample client-side OpenVPN 2.0 config file

forconnecting to multi-client server.

This configuration can be used by multiple

clients, however each client should have

its own certand keyfiles.

On Windows, you might want to rename this

file so ithas a .ovpnextension

Copy
|  | |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |``` # Specify that we are a client and that we # will be pulling certain config file directives # from the server. client
Copy
|Режим клиента, применять настройки, получаемые от сервера. |

|```

Use the same setting as you are using on

the server.

On most systems, the VPN will not function

unless you partially or fully disable

the firewall for the TUN/TAP interface.

;dev tap dev tun

Copy
|Тип интерфейса. | |``` # Windows needs the TAP-Win32 adapter name # from the Network Connections panel # if you have more than one. On XP SP2, # you may need to disable the firewall # for the TAP adapter. ;dev-node MyTap

Copy
|Специфично для Windows. |

|```

Are we connecting to a TCP or

UDP server? Use the same setting as

on the server.

;proto tcp proto udp

Copy
|Протокол. | |``` # The hostname/IP and port of the server. # You can have multiple remote entries # to load balance between the servers. remote my-server-1 1194 ;remote my-server-2 1194

Copy
|Адрес и порт сервера. Можно задать несколько адресов. |

|```

Choose a random host from the remote

list for load-balancing. Otherwise

try hosts in the order specified.

;remote-random

Copy
|Выбирать случайный адрес. Если не задано, будет перебирать серверы в порядке перечисления. | |``` # Keep trying indefinitely to resolve the # host name of the OpenVPN server. Very useful # on machines which are not permanently connected # to the internet such as laptops. resolv-retry infinite

Copy
|Запрашивать адрес в DNS при каждом подключении, полезно, если у сервера динамический адрес. |

|```

Most clients don’t need to bind to

a specific local port number.

nobind

Copy
|Для клиента привязка к определенному порту не требуется, использовать динамический порт, выделенный системой. | |``` # Downgrade privileges after initialization (non-Windows only) ;user nobody;group nobody

Copy
|Ограничить права демона заданным пользователем и группой. |

|```

Try to preserve some state across restarts.

persist-keypersist-tun

Copy
|Сохранять ключи в памяти. Не пересоздавать туннель при реконнекте. Опции требуются для работы с ограниченными правами. | |``` # If you are connecting through an # HTTP proxy to reach the actual OpenVPN # server, put the proxy server/IP and # port number here. See the man page # if your proxy server requires # authentication.

Copy
|  |

|;http-proxy-retry # retry on connection failures;http-proxy [proxy server] [proxy port #] |Подключаться через прокси-сервер. | |```

Wireless networks often produce a lot

of duplicate packets. Set this flag

to silence duplicate packet warnings.

;mute-replay-warnings ```

Copy
|Не протоколировать сообщения о повторяющихся пакетах, полезно при связи через беспроводную сеть. |

|```

SSL/TLS parms.

See the server config file for more

description. It’s best to use

a separate .crt/.key file pair

for each client. A single ca

file can be used for all clients.

|  | | ca ca.crtcert client.crtkey client.key ```

Copy
|Задаем ключи авторизации. |

|```

Verify server certificate by checking

that the certicate has the nsCertType

field set to “server”. This is an

important precaution to protect against

a potential attack discussed here:

http://openvpn.net/howto.html#mitm

To use this feature, you will need to generate

your server certificates with the nsCertType

field set to “server”. The build-key-server

script in the easy-rsa folder will do this.

;ns-cert-type serverremote-cert-tls server

Copy
|Проверка подлинности сервера. В версии 2.1 и выше рекомендуется заменить на:
remote-cert-tls server
Copy
В ранних версиях использовать:
ns-cert-type server
Copy
| |``` # If a tls-auth key is used on the server # then every client must also have the key. tls-auth ta.key 1

Copy
|Включает пакетную авторизацию, если была включена на сервере. |

|```

Select a cryptographic cipher.

If the cipher option is used on the server

then you must also specify it here.

;cipher x

Copy
|Алгоритмы шифрования, должны совпадать с сервером. | |``` # Enable compression on the VPN link. # Don't enable this unless it is also # enabled in the server config file. comp-lzo

Copy
|Использовать сжатие трафика, параметр должен совпадать с сервером. |

|```

Set log file verbosity.

verb 3

Copy
|Уровень детальности протоколирования. | |``` # Silence repeating messages ;mute 20

Copy
|Не писать в лог более заданного количества одинаковых сообщений подряд. |

|;tun-mtu 1300 ;mssfix 1300 ;fragment 1300 |Если интернет подключен через VPN, то для успешного прохождения пакетов, необходимо уменьшить размер пакета в туннеле. Задаем максимальный размер пакета, включаем корректировку размера TCP-пакетов, проходящих через туннель, и фрагментацию больших пакетов. В качестве параметра, задаем максимально допустимый размер пакета минус 50. |

Параметры запуска

Правим /etc/rc.conf: ee /etc/rc.conf Включаем запуск OpenVPN, указываем тип интерфейса, для которого необходимо загрузить драйвер, указываем путь к конфигу. openvpn_enable="YES" openvpn_if="tun" # driver(s) to load, set to "tun", "tap" or "tun tap" openvpn_configfile="/usr/local/etc/openvpn/client.conf"

Брандмауэр

Для ipfw правила будут примерно следующие: Разрешить все соединения через туннель: ipfw add allow all from any to any via tun0 Разрешаем исходящие и входящие подключения к серверу: ipfw add allow udp from any to me 1194 ipfw add allow udp from me 1194 to any

Запуск

Запускаем клиент: service openvpn start Проверяем сообщения в лог-файле: cat /var/log/messages Проверяем, открылся ли туннель: ifconfig Пингуем удаленный сервер. Пингуем хосты в сети за сервером. В случае проблем мониторим туннель: tcpdump -ni tun0 Параллельно мониторим физический канал: tcpdump -ni $pif udp port 1194 Проверяем маршруты к удаленным сетям: traceroute -P ICMP УдаленныйАдрес

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

Документация: http://openvpn.net/index.php/open-source/documentation.html