How to config openvpn config
How to config openvpn config
Creating configuration files for server and clients
Getting the sample config files
It’s best to use the OpenVPN sample configuration files as a starting point for your own configuration. These files can also be found in
Note that on Linux, BSD, or unix-like OSes, the sample configuration files are named server.conf and client.conf. On Windows they are named server.ovpn and client.ovpn.
Editing the server configuration file
The sample server configuration file is an ideal starting point for an OpenVPN server configuration. It will create a VPN using a virtual TUN network interface (for routing), will listen for client connections on UDP port 1194 (OpenVPN’s official port number), and distribute virtual addresses to connecting clients from the 10.8.0.0/24 subnet.
Before you use the sample configuration file, you should first edit the ca, cert, key, and dh parameters to point to the files you generated in the PKI section above.
At this point, the server configuration file is usable, however you still might want to customize it further:
If you want to run multiple OpenVPN instances on the same machine, each using a different configuration file, it is possible if you:
Editing the client configuration files
The sample client configuration file (client.conf on Linux/BSD/Unix or client.ovpn on Windows) mirrors the default directives set in the sample server configuration file.
Руководство по установке и настройке OpenVPN
Когда у нас появились сотрудники, работающие удаленно, пришлось думать над тем, как обеспечить им защищенный доступ к нашим хостинговым серверам, виртуальным выделенным серверам разработчиков Virtual Dedicated Server (VDS), сайтам обеспечения и сопровождения разработки и к другим ресурсам.
По соображениям безопасности доступ к этим ресурсам ограничен при помощи межсетевого экрана (файервола) по портам и адресам IP. Ежедневную перенастройку доступа при изменении динамических IP сотрудников едва ли можно назвать разумным решением.
Выход нашелся довольно быстро — это использование технологии виртуальных частных сетей Virtual Private Network (VPN) и ее свободной реализации OpenVPN. Эта реализация доступна практически для всех распространенных платформ, в том числе для планшетов и смартфонов. История развития OpenVPN насчитывает уже 12 лет (компания OpenVPN Technologies, Inc. была создана Francis Dinha и James Yona в 2002 году), так что это надежное и проверенное временем решение.
В нашей компании сеть VPN позволила предоставить защищенный доступ сотрудников к VDS, играющей роль сервера OpenVPN. И уже для фиксированного IP этого сервера был разрешен доступ к другим ресурсам компании. Попутно на сервере OpenVPN был установлен прокси Squid, что решило все проблемы доступа сотрудников с динамическими IP к защищенным ресурсам компании.
Теме OpenVPN посвящены многочисленные статьи и сообщения на форумах. Тем не менее, нужную информацию мне пришлось собирать по частям из разных мест. Попутно приходилось разбираться с многочисленными терминами и технологиями. В качестве серверов OpenVPN были использованы VDS на базе FreeBSD и Debian Linux, в качестве клиентов — рабочие станции FreeBSD, Debian Linux, Ubuntu и Microsoft Windows.
Надеюсь, что эта статья будет полезна тем, кто впервые столкнулся с необходимостью создания сети VPN или уже использует ее для решения тех или задач, а также тем, кто ищет замену коммерческим реализациям VPN.
С благодарностью приму замечания и предложения по содержимому статьи.
Оглавление
Немного теории
Если раньше для создания безопасного канала передачи данных крупным компаниям и организациям приходилось прокладывать (либо арендовать) кабели и защищать их от физического доступа злоумышленников, то теперь в этом нет необходимости. С помощью VPN можно создавать защищенные виртуальные каналы, работающие через безопасный «туннель» в Интернете. Такое решение может позволить себе любая, даже очень небольшая компания.
Конечно, если предъявляются повышенные требования к защите данных, необходимо применять сертифицированные средства и обращаться к специалистам. Однако уровень защиты, обеспечиваемый OpenVPN, позволяет использовать эту технологию для многих коммерческих приложений.
Почему сеть VPN называется виртуальной и частной?
Виртуальная она потому, что узлы сети объединяются не физическими линиями, а виртуальными соединениями, которые создаются программным обеспечением (ПО) VPN.
Сеть VPN частная, так как к ней могут подключаться только узлы компании, создавшей эту сеть, а не все желающие. На каждом узле сети VPN должно работать ПО VPN. Еще там должны находиться ключи и сертификаты, обеспечивающие узлам доступ к сети VPN и криптографическую защиту передаваемых данных.
Таким образом, сеть VPN может объединять ресурсы (серверы и рабочие станции) компании в единую безопасную виртуальную сеть, созданную на базе Интернета. И теперь сотрудники, работающие удаленно (из дома или из другой страны) будут находиться как бы в общей сети своей компании. Сеть VPN подходит и для консолидации территориально разделенных офисов компании.
Обмен данными по сети
ПО OpenVPN передает данные по сети с помощью протоколов UDP или TCP с применением драйвера TUN/TAP. Протокол UDP и драйвер TUN позволяет подключаться к серверу OpenVPN клиентам, расположенным за NAT.
Для OpenVPN можно выбрать произвольный порт, что позволяет преодолевать ограничения файервола, через который осуществляется доступ из локальной сети в Интернет (если такие ограничения установлены).
Безопасность и шифрование
Безопасность и шифрование в OpenVPN обеспечивается библиотекой OpenSSL и протоколом транспортного уровня Transport Layer Security (TLS). Вместо OpenSSL в новых версиях OpenVPN можно использовать библиотеку PolarSSL. Протокол TLS представляет собой усовершенствование протокола защищенной передачи данных уровня защищенных сокетов Secure Socket Layers (SSL).
В OpenSSL может использоваться симметричная и ассиметричная криптография.
В первом случае перед началом передачи данных на все узлы сети необходимо поместить одинаковый секретный ключ. При этом возникает проблема безопасной передачи этого ключа через небезопасный Интернет.
Во втором случае у каждого участника обмена данными есть два ключа — публичный (открытый) и приватный (секретный).
Публичный ключ используется для зашифрования данных, а приватный — для расшифрования. В основе шифрования лежит довольно сложная математика. Выбранный в SSL/TLS алгоритм зашифрования публичным ключом обеспечивает возможность расшифрования только с помощью приватного ключа.
Приватный ключ секретный, и должен оставаться в пределах узла, на котором он создан. Публичный ключ должен передаваться участникам обмена данными.
Для безопасной передачи данных необходимо идентифицировать стороны, принимающие участие в обмене данными. В противном случае можно стать жертвой так называемой «атаки посредника» (Man in the Middle, MITM). В ходе такой атаки злоумышленник подключается к каналу передачи данных и прослушивает его. Он также может вмешиваться, удалять или изменять данные.
Чтобы обеспечить аутентификацию (проверку подлинности пользователя) протокол TLS использует инфраструктуру публичных ключей (Public Key Infrastructure, PKI) и асимметричную криптографию.
Нужно осознавать, что расшифрование данных без наличия приватного ключа тоже возможно, например, методом последовательного перебора. Хотя такой метод и требует больших вычислительных ресурсов, это только вопрос времени, когда данные смогут быть расшифрованы.
Хотя размер ключа влияет на сложность расшифрования, никакой ключ не дает гарантии полной безопасности данных. Кроме того, существует возможность похищения уже расшифрованных данных и ключей за счет уязвимостей и закладок в операционной системе или прикладном ПО, а также в аппаратном обеспечении серверов и рабочих станций.
Шифрование данных увеличивает трафик и замедляет обмен данными. Чем больше длина ключа, применяемого для шифрования данных, тем труднее будет его подобрать, но и тем заметнее получится замедление обмена данными.
Сертификаты и удостоверяющий центр CA
Как мы уже сказали, при ассиметричной криптографии открытый ключ используется для зашифрования данных, а закрытый — для расшифрования. Чтобы избежать подделки открытого ключа, какая-то третья сторона должна его заверить. В результате этой процедуры создается так называемый сертификат открытого ключа.
Сертификат должна заверить организация, которой доверяют. Эта организация играет роль удостоверяющего центра (Certification authority, CA).
Если создается открытый ключ для публичного использования, в качестве удостоверяющего центра должна выступать коммерческая или государственная организация с неоспоримой репутацией. Эта организация публикует собственный открытый ключ, доступный всем.
Существует немало коммерческих организаций, выпускающих сертификаты, пригодные, например, для создания HTTPS-сайтов, для цифровой подписи сообщений электронной почты или документов, для систем мгновенного обмена сообщениями, такими как Jabber. Эти сертификаты выдаются на ограниченный срок и стоят денег.
Но для сети VPN, создаваемой для своей компании, вы можете самостоятельно создать свой удостоверяющий центр CA и выпускать так называемые самоподписанные сертификаты. Конечно, доверие к таким сертификатам не будет выходить за рамки вашей компании, но во-первых, этого будет вполне достаточно, а во-вторых, самоподписанные сертификаты совершенно бесплатны.
Самоподписанные сертификаты и будут играть роль публичных ключей, с помощью которых узлы вашей сети OpenVPN будут зашифровывать данные. Для расшифрования данных будут использованы приватные ключи.
Сертификаты создаются в соответствии со стандартом X.509. Этот стандарт определяет форматы данных и процедуры распределения открытых ключей с помощью сертификатов, снабженных электронными подписями.
Сертификат X.509 — это публичный ключ, содержащий такие данные, как субъект, владеющий сертификатом, имя узла, период действия, алгоритм и значение подписи сертификата, и т.д. Сертификат должен быть подписан приватным ключом удостоверяющего центра (Certification authority, CA).
Когда наш узел рабочей станции подключается к удаленному узлу (серверу) с использованием протокола TLS, сервер отправляет ему сертификат X.509. На нашем узле есть публичный ключ удостоверяющего центра CA, который подписал этот сертификат. Этот ключ используется для проверки подписи.
Таким образом, имеется способ проверки удаленного узла (сервера), к которому наш узел собирается подключиться, чтобы исключить «атаки посредника» MITM.
Список отзыва сертификатов
Иногда требуется блокировать доступ отдельных узлов к сети VPN компании, например, заблокировать доступ рабочей станции уволенного сотрудника.
Для упрощения этой процедуры в OpenVPN предусмотрен список отзыва сертификатов (Сertificate Revocation List, CRL) и простые средства для управления этим списком.
Список CRL создается в удостоверяющем центре CA и потом копируется на сервер OpenVPN. После внесения изменений в список CRL его необходимо повторно скопировать на сервер OpenVPN.
Файл Диффи-Хелмана
Файл Диффи-Хелмана (Diffie-Hellman) необходим для реализации одноименного протокола, позволяющего использовать небезопасный канал для получения общего секретного ключа. Этот ключ будет в дальнейшем использоваться для защищенного обмена данными с помощью алгоритмов симметричного шифрования.
В применении к OpenVPN файл Диффи-Хелмана нужен для обеспечения защиты трафика от расшифровки, если ключи были похищены. Здесь имеется в виду тот трафик, который был записан и сохранен еще до похищения ключей.
Файл Диффи-Хелмана создается на сервере OpenVPN.
Статический ключ HMAC
Статический ключ (хэш-код) аутентификации сообщений (Hash-based Message Authentication Code, HMAC) обеспечивает проверку подлинности информации, передаваемой между сторонами. Этот ключ создается на сервере OpenVPN с целью дополнительной защиты от DoS-атак и флуда.
Компоненты сети OpenVPN
Прежде чем мы перейдем от теории к практике, перечислим основные компоненты сети OpenVPN и объекты, с которыми нам придется иметь дело.
Удостоверяющий центр CA
Выдает сертификаты по запросу узлов сети VPN, подписанные сертификатом удостоверяющего центра. Предоставляет узлам сети VPN свой собственный сертификат для проверки удостоверяющей стороны. Управляет списком отзыва сертификатов CRL.
ПО сервера OpenVPN создает туннель внутри незащищенной сети, например, Интернета. Этот туннель обеспечивает безопасный зашифрованный трафик между узлами — участниками обмена данными в сети OpenVPN.
ПО клиента OpenVPN устанавливается на все узлы, которым необходим защищенный канал передачи данный с сервером OpenVPN. При соответствующей настройке сервера OpenVPN возможна защищенная передача данных между клиентами OpenVPN, а не только между клиентами и сервером OpenVPN.
Сертификаты (публичные ключи) X.509
Сертификаты X.509 представляют собой публичные ключи, заверенные удостоверяющим центром CA. Они используются для зашифровывания данных. Факт заверения сертификата удостоверяющим центром CA позволяет идентифицировать сторону, передающую зашифрованные данные.
Файл запроса на сертификат создается на узлах сети, затем он переносится на узел удостоверяющего центра и там подписывается. Созданный в результате подписанный сертификат переносится обратно на запросивший его узел сети OpenVPN.
Приватные ключи секретные. Они должны создаваться и храниться на каждом узле сети OpenVPN, предназначены для расшифрования данных и никогда не должны передаваться по сети.
Приватные ключи создаются на узлах сети OpenVPN одновременно с файлом запроса на получение сертификата.
Список отзыва сертификатов CRL
Содержит список сертификатов, утративших доверие. Он создается и редактируется на узле удостоверяющего центра CA. Чтобы отключить узел от сети, достаточно занести его сертификат в список CRL.
После создания и каждого изменения список CRL переносится на серверы OpenVPN.
Используется, чтобы в случае похищения ключей исключить расшифрование трафика, записанного еще до этого похищения. Создается на сервере OpenVPN.
Статический ключ HMAC
Служит для проверки подлинности передаваемой информации. Обеспечивает защиту от DoS-атак и флуда. Создается на сервере OpenVPN.
Готовим оборудование для установки OpenVPN
Если вы впервые настраиваете сеть VPN, лучше всего экспериментировать на виртуальных машинах VDS. Это могут быть VDS, созданные локально на вашем компьютере или на сервере в вашей сети, либо арендованные у провайдера. Перед арендой VDS поинтересуйтесь, поддерживается ли драйвер TUN/TAP. Некоторые провайдеры требуют дополнительной оплаты для подключения TUN/TAP.
На рис. 1. мы показали схему стенда, на котором будем устанавливать компоненты и узлы OpenVPN (имена и адреса IP хостов могут быть другими).
Рис. 1. Стенд для изучения OpenVPN.
Здесь изображены три узла (хоста), для каждого из которых потребуется отдельный VDS:
Хосты клиента и сервера VPN соединены обычным, небезопасным каналом. В случае макета это может быть локальная сеть, в реальной жизни — канал сети Интернет. ПО OpenVPN создает в этой сети канал, обозначенный на рис. 1 красным цветом, внутри которого устанавливается безопасный шифрованный канал (обозначен зеленым цветом).
В макете хост удостоверяющего центра CA можно подключить к вашей локальной сети. Для реальной работы хост CA нужно отсоединить от сети, а обмен сертификатами и ключами осуществлять с помощью, например, USB флэш-диска.
Если к безопасности предъявляются повышенные требования, хост CA необходимо поместить в охраняемое помещение — расположенная на этой машине информация позволяет создавать ключи доступа к вашей сети VPN.
Мы проводили установку серверов OpenVPN в среде ОС Debian Linux и FreeBSD, клиентов OpenVPN в ОС Debian Linux, FreeBSD и Microsoft Windows.
Основная часть статьи посвящена установке компонентов OpenVPN для Debian Linux. Далее мы рассмотрим особенности установки для FreeBSD и Microsoft Windows.
По возможности на узлах сети OpenVPN используйте новые версии ОС. Перед тем как приступить к работе с OpenVPN, обновите пакеты Linux:
Установите на всех узлах пакет пакет zip, если он не был установлен ранее:
Этот пакет будет нужен для распаковки архива утилиты Easy-RSA, с помощью которой мы будем создавать ключи и сертификаты.
На всех узлах настройте обновление и синхронизацию времени.
Синхронизация времени необходима, т.к. сертификаты имеют период действия. Если часы, например, на хосте удостоверяющего центра CA и сервера OpenVPN не синхронны, может получиться так, что выданный удостоверяющим центром сертификат не будет действителен на узлах сети OpenVPN из-за ограничений по дате или времени.
Дальнейшие работы мы начнем с подготовки хоста удостоверяющего центра CA. Затем установим хосты сервера и клиента OpenVPN.
Создание удостоверяющего центра CA
Как мы уже говорили, задача удостоверяющего центра CA — выдача подписанных сертификатов для сервера и клиентов OpenVPN.
Чтобы получить сертификат, сервер или клиент на своем хосте генерирует файл запроса на сертификат. Этот файл запроса передается на хост CA, который создает сертификат и подписывает его. Далее подписанный сертификат передается на запросивший хост.
Одновременно с запросом сертификата создается приватный ключ. Приватные ключи создаются для всех узлов сети OpenVPN: для удостоверяющего центра CA, для сервера и всех клиентов OpenVPN.
Для безопасности файлы ключей никогда не должны покидать узлы, где они были созданы. Обмениваться можно только запросами на сертификаты и сертификатами, приватными ключами обмениваться нельзя и незачем.
На рис. 2 показан процесс получения подписанного сертификата для сервера OpenVPN.
Рис. 2. Получение сертификата для сервера OpenVPN
Сервер OpenVPN создает свой приватный ключ и файл запроса на получение сертификата. Файл запроса передается в удостоверяющий центр, например, на USB флеш-диске.
Удостоверяющий центр на основе запроса создает подписанный сертификат, который затем требуется перенести на сервер OpenVPN, также на USB флэш-диске.
Если к безопасности не предъявляется особых требований или вы только изучаете OpenVPN, можно подключить машину удостоверяющего центра к сети и передавать запросы и сертификаты, например, с помощью утилит SFTP или SCP. Можно даже совместить функции CA и, например, сервера OpenVPN в одном хосте.
Аналогичным образом необходимо получить сертификаты для всех клиентских узлов (рис. 3).
Рис. 3. Получение сертификата для клиента OpenVPN
Установка утилиты Easy-RSA
Все операции по созданию ключей и сертификатов можно выполнить с помощью утилиты openssl. Однако проще воспользоваться специально созданной для этого программой Easy-RSA, которая использует openssl для выполнения действий с ключами и сертификатами.
Ранее утилита Easy-RSA поставлялась вместе с OpenVPN, но теперь это отдельный проект.
Все операции с удостоверяющим центром и сертификатами можно (и нужно) проводить от имени непривилегированного пользователя.
Создайте пользователя с именем, например, ca и перейдите в его домашний каталог:
Загрузите дистрибутив программы утилитой wget.
После загрузки распакуйте архив master.zip:
В табл. 1 перечислены файлы и каталоги, входящие в дистрибутив Easy-RSA.
Таблица 1. Состав дистрибутива Easy-RSA.
How to configure OpenVPN Access Server
Introduction
This document provides an overview of the OpenVPN Access Server Client Web UI, Admin Web UI, and command line interface (CLI). Once you are familiar with these, these links provide more information on configuring your server:
If you’re having trouble accessing the web interface, refer to: Troubleshooting access to the web interface.
The Client Web UI
OpenVPN Access Server provides web services to run both the Admin Web UI and the Client Web UI. The Client Web UI provides your users with pre-configured VPN clients, which simplifies the process of connecting to your VPN server.
To access the Client Web UI, use either the IP address or hostname of your Access Server. For example:
The IP address is the external IP address of your server. A custom hostname can be set up using the Admin Web UI and a DNS ‘A’ record. You can follow the steps to set up a custom hostname here: Setting up your OpenVPN Access Server hostname.
The Admin Web UI
The Admin Web UI is available at the same IP address or hostname that the Client Web UI uses, but at the /admin path. For example:
Once you finish the setup, the credentials and address for the web interface are printed on screen:
Note: Access Server versions older than 2.10 do not automatically generate a password. On older versions you set the password manually by typing passwd openvpn on the command line.
Note: The root user credentials can’t be used to sign in to the Admin Web UI.
For more information about the features in the Admin Web UI, refer to the OpenVPN Access Server Admin Manual.
Admin Web UI Features
These sections provide an introduction to the Admin Web UI and how you can retrieve the server status, a configuration overview, and the number of current connected users. There are details on an easy way to query the log database and what the log reports look like.
Server Status
The Status Overview section indicates whether the VPN server is currently on or off. If it’s on, you can click on Stop the Server to stop the OpenVPN daemons. If the server is off, you can click on Start the Server to start the OpenVPN daemons.
Stopping or starting the daemons won’t affect the Admin Web UI service — it continues to actively listen on its configured port, which is by default TCP port 943. However, if you stop the daemons, this also stops the automatic internal routing of browser traffic to the standard HTTPS port TCP 443. With internal routing turned off, you must specify port 943 to access your Admin Web UI. For example:
Active Configuration
The Active Configuration section displays some important configuration settings that are managed in the configuration and authentication sections of the Admin Web UI.
Current Users
The Current Users section displays actively connected users with information in the following columns:
Common Name | The username. |
Real Address | The originating IP address of the connecting client. |
VPN Address | The IP address assigned by your OpenVPN Access Server. |
Bytes Sent Received | The data (in bytes) received and sent through the VPN tunnel. |
Connected Since | When the currently active connection was last connected or reconnected. |
Block | Block the user, denying access to the VPN. |
If an administrator blocks a user from the Current Users page, that block can be removed by unchecking the Deny Access box on User Management > User Permissions.
Querying the log database
The Log Reports section displays the log in your browser and provides the option to download it as a comma separated values (CSV) file. You can query your logs or filter the output using the fields under Query by Start Time and Filter by Number of Log Entries. You can also filter your results based on any text you enter into the filter records field.
There is a log database available through the CLI interface called logdba, which you can use to extract and export information.
Query log results
The results of a log query display below search and filter fields with information in the following columns:
Node | The name of the OpenVPN Access Server. This is different for a multi-server setup, where the node name is different for each server. |
Username | The username of the client connection, as authenticated by Access Server |
Start Time | The date and time that a specific connection or attempted connection occurred. |
Duration | The length in time of the connection. Note: When a user’s connection is momentarily interrupted, a new, separate session is logged. |
Service | One of the following: VPN: Clients connecting through the OpenVPN daemon using a client. WEB_CLIENT: Users signing into, or attempting to sign into the client web server using a browser. WEB_ADMIN: Users signing into, or attempting to sign into the admin web server or Admin Web UI using a browser. XML_API: Any XML-RPC API requests are logged with this service when the XML debug flag is enabled. |
Real IP | The real IP address of the client connected to the Access Server or the user attempting to connect to a web service. |
VPN IP | The IP address assigned to the client by the Access Server. |
Proto | The protocol used for the OpenVPN tunnel itself — UDP is generally the better choice here. |
Port | The port the client connected on — the default ports are TCP 443 and UDP 1194. |
Bytes In | The total number of bytes sent from the client to the Access Server. |
Bytes Out | The total number of bytes sent from the Access Server to the client. |
Error | Any error messages display here, usually in short and technical phrases. |
Admin Web UI User Manual
For more information about each Admin Web UI section, refer to the OpenVPN Access Server Admin Manual, which provides details about the different configuration options through your Admin Web UI portal as well as details on typical network configurations.
The Command Line Interface (CLI)
You can use the CLI to manage all of the Access Server VPN settings. And, the CLI enables you to use more advanced functions that aren’t available through the Admin Web UI.
Access to the CLI is typically established through an SSH session to your server or directly on your server’s console. On the CLI you can create your own shell scripts to automate tasks such as creating new users with custom settings or implementing custom authentication options.
For more information on using the CLI, refer to Access Server command line interface tools.
OpenVPN TM 2.0 HOWTO
Introduction
OpenVPN is a full-featured SSL VPN which implements OSI layer 2 or 3 secure network extension using the industry standard SSL/TLS protocol, supports flexible client authentication methods based on certificates, smart cards, and/or username/password credentials, and allows user or group-specific access control policies using firewall rules applied to the VPN virtual interface. OpenVPN is not a web application proxy and does not operate through a web browser.
OpenVPN 2.0 expands on the capabilities of OpenVPN 1.x by offering a scalable client/server mode, allowing multiple clients to connect to a single OpenVPN server process over a single TCP or UDP port.
This document provides step-by-step instructions for configuring an OpenVPN 2.0 client/server VPN, including:
The impatient may wish to jump straight to the sample configuration files:
Intended Audience
This HOWTO assumes that readers possess a prior understanding of basic networking concepts such as IP addresses, DNS names, netmasks, subnets, IP routing, routers, network interfaces, LANs, gateways, and firewall rules.
If you don’t have a handle on these basics, but would still like to set up OpenVPN, I would encourage you to hire an OpenVPN expert on a consulting basis. Many of the authors on the articles page are available for consulting, or you can contact the creators of OpenVPN at info@openvpn.net.
Additional Documentation
OpenVPN Books
OpenVPN 1.x HOWTO
The original OpenVPN 1.x HOWTO is still available, and remains relevant for point-to-point or static-key configurations.
OpenVPN Articles
For additional documentation, see the articles page.
OpenVPN Quickstart
While this HOWTO will guide you in setting up a scalable client/server VPN using an X509 PKI (public key infrastruction using certificates and private keys), this might be overkill if you are only looking for a simple VPN setup with a server that can handle a single client.
If you would like to get a VPN running quickly with mimimal configuration, you might check out the Static Key Mini-HOWTO.
Static Key advantages
Static Key disadvantages
Installing OpenVPN
For security, it’s a good idea to check the file release signature after downloading.
The OpenVPN executable should be installed on both server and client machines, since the single executable provides both client and server functions.
Linux Notes (using RPM package)
If you are using a Linux distribution which supports RPM packages (SuSE, Fedora, Redhat, etc.), it’s best to install using this mechanism. The easiest method is to find an existing binary RPM file for your distribution. You can also build your own binary RPM file:
or upgrade an existing installation with
Installing OpenVPN from a binary RPM package has these dependencies:
Furthermore, if you are building your own binary RPM package, there are several additional dependencies:
See the openvpn.spec file for additional notes on building an RPM package for Red Hat Linux 9 or building with reduced dependencies.
Linux Notes (without RPM)
If you are using Debian, Gentoo, or a non-RPM-based Linux distribution, use your distro-specific packaging mechanism such as apt-get on Debian or emerge on Gentoo.
Then cd to the top-level directory and type:
Windows Notes
OpenVPN for Windows can be installed from the self-installing exe file on the OpenVPN download page. Remember that OpenVPN will only run on Windows 2000 or later. Also note that OpenVPN must be installed and run by a user who has administrative privileges (this restriction is imposed by Windows, not OpenVPN). The restriction can be sidestepped by running OpenVPN in the background as a service, in which case even non-admin users will be able to access the VPN, once it is installed. More discussion on OpenVPN + Windows privilege issues.
OpenVPN can also be installed as a GUI on Windows, using Mathias Sundman’s installation package, which will install both OpenVPN and the Windows GUI.
After you run the Windows installer, OpenVPN is ready to use and will associate itself with files having the .ovpn extension. To run OpenVPN, you can:
Right click on an OpenVPN configuration file (.ovpn) and select Start OpenVPN on this configuration file. Once running, you can use the F4 key to exit.
Run OpenVPN from a command prompt Window with a command such as:
Once running in a command prompt window, OpenVPN can be stopped by the F4 key.
A GUI is also available for the Windows version of OpenVPN.
Mac OS X Notes
Angelo Laub and Dirk Theisen have developed an OpenVPN GUI for OS X.
Other OSes
Some notes are available in the INSTALL file for specific OSes. In general, the
method can be used, or you can search for an OpenVPN port or package which is specific to your OS/distribution.
Determining whether to use a routed or bridged VPN
See FAQ for an overview of Routing vs. Ethernet Bridging. See also the OpenVPN Ethernet Bridging page for more notes and details on bridging.
Overall, routing is probably a better choice for most people, as it is more efficient and easier to set up (as far as the OpenVPN configuration itself) than bridging. Routing also provides a greater ability to selectively control access rights on a client-specific basis.
I would recommend using routing unless you need a specific feature which requires bridging, such as:
Numbering private subnets
Setting up a VPN often entails linking together private subnets from different locations.
The Internet Assigned Numbers Authority (IANA) has reserved the following three blocks of the IP address space for private internets (codified in RFC 1918):
10.0.0.0 | 10.255.255.255 | (10/8 prefix) |
172.16.0.0 | 172.31.255.255 | (172.16/12 prefix) |
192.168.0.0 | 192.168.255.255 | (192.168/16 prefix) |
While addresses from these netblocks should normally be used in VPN configurations, it’s important to select addresses that minimize the probability of IP address or subnet conflicts. The types of conflicts that need to be avoided are:
For example, suppose you use the popular 192.168.0.0/24 subnet as your private LAN subnet. Now you are trying to connect to the VPN from an internet cafe which is using the same subnet for its WiFi LAN. You will have a routing conflict because your machine won’t know if 192.168.0.1 refers to the local WiFi gateway or to the same address on the VPN.
As another example, suppose you want to link together multiple sites by VPN, but each site is using 192.168.0.0/24 as its LAN subnet. This won’t work without adding a complexifying layer of NAT translation, because the VPN won’t know how to route packets between multiple sites if those sites don’t use a subnet which uniquely identifies them.
The best solution is to avoid using 10.0.0.0/24 or 192.168.0.0/24 as private LAN network addresses. Instead, use something that has a lower probability of being used in a WiFi cafe, airport, or hotel where you might expect to connect from remotely. The best candidates are subnets in the middle of the vast 10.0.0.0/8 netblock (for example 10.66.77.0/24).
And to avoid cross-site IP numbering conflicts, always use unique numbering for your LAN subnets.
Setting up your own Certificate Authority (CA) and generating certificates and keys for an OpenVPN server and multiple clients
Overview
The first step in building an OpenVPN 2.0 configuration is to establish a PKI (public key infrastructure). The PKI consists of:
OpenVPN supports bidirectional authentication based on certificates, meaning that the client must authenticate the server certificate and the server must authenticate the client certificate before mutual trust is established.
Both server and client will authenticate the other by first verifying that the presented certificate was signed by the master certificate authority (CA), and then by testing information in the now-authenticated certificate header, such as the certificate common name or certificate type (client or server).
This security model has a number of desirable features from the VPN perspective:
Generate the master Certificate Authority (CA) certificate & key
In this section we will generate a master CA certificate/key, a server certificate/key, and certificates/keys for 3 separate clients.
For PKI management, we will use a set of scripts bundled with OpenVPN.
If you are using Windows, open up a Command Prompt window and cd to \Program Files\OpenVPN\easy-rsa. Run the following batch file to copy configuration files into place (this will overwrite any preexisting vars.bat and openssl.cnf files):
Now edit the vars file (called vars.bat on Windows) and set the KEY_COUNTRY, KEY_PROVINCE, KEY_CITY, KEY_ORG, and KEY_EMAIL parameters. Don’t leave any of these parameters blank.
Next, initialize the PKI. On Linux/BSD/Unix:
The final command (build-ca) will build the certificate authority (CA) certificate and key by invoking the interactive openssl command:
Note that in the above sequence, most queried parameters were defaulted to the values set in the vars or vars.bat files. The only parameter which must be explicitly entered is the Common Name. In the example above, I used «OpenVPN-CA».
Generate certificate & key for server
Next, we will generate a certificate and private key for the server. On Linux/BSD/Unix:
As in the previous step, most parameters can be defaulted. When the Common Name is queried, enter «server». Two other queries require positive responses, «Sign the certificate? [y/n]» and «1 out of 1 certificate requests certified, commit? [y/n]».
Generate certificates & keys for 3 clients
Generating client certificates is very similar to the previous step. On Linux/BSD/Unix:
If you would like to password-protect your client keys, substitute the build-key-pass script.
Remember that for each client, make sure to type the appropriate Common Name when prompted, i.e. «client1», «client2», or «client3». Always use a unique common name for each client.
Generate Diffie Hellman parameters
Diffie Hellman parameters must be generated for the OpenVPN server. On Linux/BSD/Unix:
Key Files
Now we will find our newly-generated keys and certificates in the keys subdirectory. Here is an explanation of the relevant files:
Filename | Needed By | Purpose | Secret |
ca.crt | server + all clients | Root CA certificate | NO |
ca.key | key signing machine only | Root CA key | YES |
dh | server only | Diffie Hellman parameters | NO |
server.crt | server only | Server Certificate | NO |
server.key | server only | Server Key | YES |
client1.crt | client1 only | Client1 Certificate | NO |
client1.key | client1 only | Client1 Key | YES |
client2.crt | client2 only | Client2 Certificate | NO |
client2.key | client2 only | Client2 Key | YES |
client3.crt | client3 only | Client3 Certificate | NO |
client3.key | client3 only | Client3 Key | YES |
The final step in the key generation process is to copy all files to the machines which need them, taking care to copy secret files over a secure channel.
Now wait, you may say. Shouldn’t it be possible to set up the PKI without a pre-existing secure channel?
The answer is ostensibly yes. In the example above, for the sake of brevity, we generated all private keys in the same place. With a bit more effort, we could have done this differently. For example, instead of generating the client certificate and keys on the server, we could have had the client generate its own private key locally, and then submit a Certificate Signing Request (CSR) to the key-signing machine. In turn, the key-signing machine could have processed the CSR and returned a signed certificate to the client. This could have been done without ever requiring that a secret .key file leave the hard drive of the machine on which it was generated.
Creating configuration files for server and clients
Getting the sample config files
It’s best to use the OpenVPN sample configuration files as a starting point for your own configuration. These files can also be found in
Note that on Linux, BSD, or unix-like OSes, the sample configuration files are named server.conf and client.conf. On Windows they are named server.ovpn and client.ovpn.
Editing the server configuration file
The sample server configuration file is an ideal starting point for an OpenVPN server configuration. It will create a VPN using a virtual TUN network interface (for routing), will listen for client connections on UDP port 1194 (OpenVPN’s official port number), and distribute virtual addresses to connecting clients from the 10.8.0.0/24 subnet.
Before you use the sample configuration file, you should first edit the ca, cert, key, and dh parameters to point to the files you generated in the PKI section above.
At this point, the server configuration file is usable, however you still might want to customize it further:
If you want to run multiple OpenVPN instances on the same machine, each using a different configuration file, it is possible if you:
Editing the client configuration files
The sample client configuration file (client.conf on Linux/BSD/Unix or client.ovpn on Windows) mirrors the default directives set in the sample server configuration file.
Like the server configuration file, first edit the ca, cert, and key parameters to point to the files you generated in the PKI section above. Note that each client should have its own cert/key pair. Only the ca file is universal across the OpenVPN server and all clients.
Next, edit the remote directive to point to the hostname/IP address and port number of the OpenVPN server (if your OpenVPN server will be running on a single-NIC machine behind a firewall/NAT-gateway, use the public IP address of the gateway, and a port number which you have configured the gateway to forward to the OpenVPN server).
Finally, ensure that the client configuration file is consistent with the directives used in the server configuration. The major thing to check for is that the dev (tun or tap) and proto (udp or tcp) directives are consistent. Also make sure that comp-lzo and fragment, if used, are present in both client and server config files.
Starting up the VPN and testing for initial connectivity
Starting the server
First, make sure the OpenVPN server will be accessible from the internet. That means:
To simplify troubleshooting, it’s best to initially start the OpenVPN server from the command line (or right-click on the .ovpn file on Windows), rather than start it as a daemon or service:
A normal server startup should look like this (output will vary across platforms):
Starting the client
As in the server configuration, it’s best to initially start the OpenVPN server from the command line (or on Windows, by right-clicking on the client.ovpn file), rather than start it as a daemon or service:
A normal client startup on Windows will look similar to the server output above, and should end with the Initialization Sequence Completed message.
Now, try a ping across the VPN from the client. If you are using routing (i.e. dev tun in the server config file), try:
If you are using bridging (i.e. dev tap in the server config file), try to ping the IP address of a machine on the server’s ethernet subnet.
If the ping succeeds, congratulations! You now have a functioning VPN.
Troubleshooting
If the ping failed or the OpenVPN client initialization failed to complete, here is a checklist of common symptoms and their solutions:
You get the error message: TLS Error: TLS key negotiation failed to occur within 60 seconds (check your network connectivity). This error indicates that the client was unable to establish a network connection with the server.
Solution: Start the DHCP client server and make sure that you are using a personal firewall which is known to work correctly on XP SP2.
The connection stalls on startup when using a proto udp configuration, the server log file shows this line:
however the client log does not show an equivalent line.
Solution: You have a one-way connection from client to server. The server to client direction is blocked by a firewall, usually on the client side. The firewall can either be (a) a personal software firewall running on the client, or (b) the NAT router gateway for the client. Modify the firewall to allow returning UDP packets from the server to reach the client.
See the FAQ for additional troubleshooting information.
Configuring OpenVPN to run automatically on system startup
The lack of standards in this area means that most OSes have a different way of configuring daemons/services for autostart on boot. The best way to have this functionality configured by default is to install OpenVPN as a package, such as via RPM on Linux or using the Windows installer.
Linux
If you install OpenVPN via an RPM package on Linux, the installer will set up an initscript. When executed, the initscript will scan for .conf configuration files in /etc/openvpn, and if found, will start up a separate OpenVPN daemon for each file.
Windows
The Windows installer will set up a Service Wrapper, but leave it turned off by default. To activate it, go to Control Panel / Administrative Tools / Services, select the OpenVPN service, right-click on properties, and set the Startup Type to Automatic. This will configure the service for automatic start on the next reboot.
When started, the OpenVPN Service Wrapper will scan the \Program Files\OpenVPN\config folder for .ovpn configuration files, starting a separate OpenVPN process on each file.
Controlling a running OpenVPN process
Running on Linux/BSD/Unix
OpenVPN accepts several signals:
Use the writepid directive to write the OpenVPN daemon’s PID to a file, so that you know where to send the signal (if you are starting openvpn with an initscript, the script may already be passing a —writepid directive on the openvpn command line).
Running on Windows as a GUI
Running in a Windows command prompt window
On Windows, you can start OpenVPN by right clicking on an OpenVPN configuration file (.ovpn file) and selecting «Start OpenVPN on this config file».
Once running in this fashion, several keyboard commands are available:
Running as a Windows Service
When OpenVPN is started as a service on Windows, the only way to control it is:
Modifying a live server configuration
While most configuration changes require you to restart the server, there are two directives in particular which refer to files which can be dynamically updated on-the-fly, and which will take immediate effect on the server without needing to restart the server process.
Status File
The default server.conf file has a line
which will output a list of current client connections to the file openvpn-status.log once per minute.
Using the management interface
The OpenVPN management interface allows a great deal of control over a running OpenVPN process. You can use the management interface directly, by telneting to the management interface port, or indirectly by using an OpenVPN GUI which itself connects to the management interface.
To enable the management interface on either an OpenVPN server or client, add this to the configuration file:
Once OpenVPN is running, you can connect to the management interface using a telnet client. For example:
Expanding the scope of the VPN to include additional machines on either the client or server subnet.
Including multiple machines on the server side when using a routed VPN (dev tun)
Once the VPN is operational in a point-to-point capacity between client and server, it may be desirable to expand the scope of the VPN so that clients can reach multiple machines on the server network, rather than only the server machine itself.
For the purpose of this example, we will assume that the server-side LAN uses a subnet of 10.66.0.0/24 and the VPN IP address pool uses 10.8.0.0/24 as cited in the server directive in the OpenVPN server configuration file.
First, you must advertise the 10.66.0.0/24 subnet to VPN clients as being accessible through the VPN. This can easily be done with the following server-side config file directive:
Next, you must set up a route on the server-side LAN gateway to route the VPN client subnet (10.8.0.0/24) to the OpenVPN server (this is only necessary if the OpenVPN server and the LAN gateway are different machines).
Make sure that you’ve enabled IP and TUN/TAP forwarding on the OpenVPN server machine.
Including multiple machines on the server side when using a bridged VPN (dev tap)
One of the benefits of using ethernet bridging is that you get this for free without needing any additional configuration.
Including multiple machines on the client side when using a routed VPN (dev tun)
In a typical road-warrior or remote access scenario, the client machine connects to the VPN as a single machine. But suppose the client machine is a gateway for a local LAN (such as a home office), and you would like each machine on the client LAN to be able to route through the VPN.
For this example, we will assume that the client LAN is using the 192.168.4.0/24 subnet, and that the VPN client is using a certificate with a common name of client2. Our goal is to set up the VPN so that any machine on the client LAN can communicate with any machine on the server LAN through the VPN.
Before setup, there are some basic prerequisites which must be followed:
First, make sure that IP and TUN/TAP forwarding is enabled on the client machine.
Next, we will deal with the necessary configuration changes on the server side. If the server configuration file does not currently reference a client configuration directory, add one now:
In the above directive, ccd should be the name of a directory which has been pre-created in the default directory where the OpenVPN server daemon runs. On Linux this tends to be /etc/openvpn and on Windows it is usually \Program Files\OpenVPN\config. When a new client connects to the OpenVPN server, the daemon will check this directory for a file which matches the common name of the connecting client. If a matching file is found, it will be read and processed for additional configuration file directives to be applied to the named client.
The next step is to create a file called client2 in the ccd directory. This file should contain the line:
This will tell the OpenVPN server that the 192.168.4.0/24 subnet should be routed to client2.
Next, add the following line to the main server config file (not the ccd/client2 file):
Why the redundant route and iroute statements, you might ask? The reason is that route controls the routing from the kernel to the OpenVPN server (via the TUN interface) while iroute controls the routing from the OpenVPN server to the remote clients. Both are necessary.
Next, ask yourself if you would like to allow network traffic between client2’s subnet (192.168.4.0/24) and other clients of the OpenVPN server. If so, add the following to the server config file.
This will cause the OpenVPN server to advertise client2’s subnet to other connecting clients.
The last step, and one that is often forgotten, is to add a route to the server’s LAN gateway which directs 192.168.4.0/24 to the OpenVPN server box (you won’t need this if the OpenVPN server box is the gateway for the server LAN). Suppose you were missing this step and you tried to ping a machine (not the OpenVPN server itself) on the server LAN from 192.168.4.8? The outgoing ping would probably reach the machine, but then it wouldn’t know how to route the ping reply, because it would have no idea how to reach 192.168.4.0/24. The rule of thumb to use is that when routing entire LANs through the VPN (when the VPN server is not the same machine as the LAN gateway), make sure that the gateway for the LAN routes all VPN subnets to the VPN server machine.
Similarly, if the client machine running OpenVPN is not also the gateway for the client LAN, then the gateway for the client LAN must have a route which directs all subnets which should be reachable through the VPN to the OpenVPN client machine.
Including multiple machines on the client side when using a bridged VPN (dev tap)
This requires a more complex setup (maybe not more complex in practice, but more complicated to explain in detail):
Pushing DHCP options to clients
The OpenVPN server can push DHCP options such as DNS and WINS server addresses to clients (some caveats to be aware of). Windows clients can accept pushed DHCP options natively, while non-Windows clients can accept them by using a client-side up script which parses the foreign_option_n environmental variable list. See the man page or openvpn-users mailing list archive for non-Windows foreign_option_n documentation and script examples.
For example, suppose you would like connecting clients to use an internal DNS server at 10.66.0.4 or 10.66.0.5 and a WINS server at 10.66.0.8. Add this to the OpenVPN server configuration:
To test this feature on Windows, run the following from a command prompt window after the machine has connected to an OpenVPN server:
The entry for the TAP-Win32 adapter should show the DHCP options which were pushed by the server.
Configuring client-specific rules and access policies
Suppose we are setting up a company VPN, and we would like to establish separate access policies for 3 different classes of users:
The basic approach we will take is (a) segregate each user class into its own virtual IP address range, and (b) control access to machines by setting up firewall rules which key off the client’s virtual IP address.
In our example, suppose that we have a variable number of employees, but only one system administrator, and two contractors. Our IP allocation approach will be to put all employees into an IP address pool, and then allocate fixed IP addresses for the system administrator and contractors.
Note that one of the prerequisites of this example is that you have a software firewall running on the OpenVPN server machine which gives you the ability to define specific firewall rules. For our example, we will assume the firewall is Linux iptables.
First, let’s create a virtual IP address map according to user class:
Class | Virtual IP Range | Allowed LAN Access | Common Names |
Employees | 10.8.0.0/24 | Samba/email server at 10.66.4.4 | [variable] |
System Administrators | 10.8.1.0/24 | Entire 10.66.4.0/24 subnet | sysadmin1 |
Contractors | 10.8.2.0/24 | Contractor server at 10.66.4.12 | contractor1, contracter2 |
Next, let’s translate this map into an OpenVPN server configuration. First of all, make sure you’ve followed the steps above for making the 10.66.4.0/24 subnet available to all clients (while we will configure routing to allow client access to the entire 10.66.4.0/24 subnet, we will then impose access restrictions using firewall rules to implement the above policy table).
First, define a static unit number for our tun interface, so that we will be able to refer to it later in our firewall rules:
In the server configuration file, define the Employee IP address pool:
Add routes for the System Administrator and Contractor IP ranges:
Because we will be assigning fixed IP addresses for specific System Administrators and Contractors, we will use a client configuration directory:
Now place special configuration files in the ccd subdirectory to define the fixed IP address for each non-Employee VPN client.
ccd/sysadmin1
ccd/contractor1
ccd/contractor2
Each pair of ifconfig-push addresses represent the virtual client and server IP endpoints. They must be taken from successive /30 subnets in order to be compatible with Windows clients and the TAP-Win32 driver. Specifically, the last octet in the IP address of each endpoint pair must be taken from this set:
This completes the OpenVPN configuration. The final step is to add firewall rules to finalize the access policy. For this example, we will use firewall rules in the Linux iptables syntax:
Using alternative authentication methods
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.
Next, configure the server to use an authentication plugin, which may be a script, shared object, or DLL. The OpenVPN server will call the plugin every time a VPN client tries to connect, passing it the username/password entered on the client. The authentication plugin can control whether or not the OpenVPN server allows the client to connect by returning a failure (1) or success (0) value.
Using Script Plugins
Script plugins can be used by adding the auth-user-pass-verify directive to the server-side configuration file. For example:
will use the auth-pam.pl perl script to authenticate the username/password of connecting clients. See the description of auth-user-pass-verify in the manual page for more information.
The auth-pam.pl script is included in the OpenVPN source file distribution in the sample-scripts subdirectory. It will authenticate users on a Linux server using a PAM authentication module, which could in turn implement shadow password, RADIUS, or LDAP authentication. auth-pam.pl is primarily intended for demonstration purposes. For real-world PAM authentication, use the openvpn-auth-pam shared object plugin described below.
Using Shared Object or DLL Plugins
Shared object or DLL plugins are usually compiled C modules which are loaded by the OpenVPN server at run time. For example if you are using an RPM-based OpenVPN package on Linux, the openvpn-auth-pam plugin should be already built. To use it, add this to the server-side config file:
This will tell the OpenVPN server to validate the username/password entered by clients using the login PAM module.
For real-world production use, it’s better to use the openvpn-auth-pam plugin, because it has several advantages over the auth-pam.pl script:
If you would like more information on developing your own plugins for use with OpenVPN, see the README files in the plugin subdirectory of the OpenVPN source distribution.
To build the openvpn-auth-pam plugin on Linux, cd to the plugin/auth-pam directory in the OpenVPN source distribution and run make.
Using username/password authentication as the only form of client authentication
By default, using auth-user-pass-verify or a username/password-checking plugin on the server will enable dual authentication, requiring that both client-certificate and username/password authentication succeed in order for the client to be authenticated.
While it is discouraged from a security perspective, it is also possible to disable the use of client certificates, and force username/password authentication only. On the server:
Such configurations should usually also set:
which will tell the server to use the username for indexing purposes as it would use the Common Name of a client which was authenticating via a client certificate.
Note that client-cert-not-required will not obviate the need for a server certificate, so a client connecting to a server which uses client-cert-not-required may remove the cert and key directives from the client configuration file, but not the ca directive, because it is necessary for the client to verify the server certificate.
How to add dual-factor authentication to an OpenVPN configuration using client-side smart cards
About dual-factor authentication
Dual-factor authentication is a method of authentication that combines two elements: something you have and something you know.
Something you have should be a device that cannot be duplicated; such a device can be a cryptographic token that contains a private secret key. This private key is generated inside the device and never leaves it. If a user possessing this token attempts to access protected services on a remote network, the authorization process which grants or denies network access can establish, with a high degree of certainty, that the user seeking access is in physical possession of a known, certified token.
Something you know can be a password presented to the cryptographic device. Without presenting the proper password you cannot access the private secret key. Another feature of cryptographic devices is to prohibit the use of the private secret key if the wrong password had been presented more than an allowed number of times. This behavior ensures that if a user lost his device, it would be infeasible for another person to use it.
Cryptographic devices are commonly called «smart cards» or «tokens», and are used in conjunction with a PKI (Public Key Infrastructure). The VPN server can examine a X.509 certificate and verify that the user holds the corresponding private secret key. Since the device cannot be duplicated and requires a valid password, the server is able to authenticate the user with a high degree of confidence.
Dual-factor authentication is much stronger than password-based authentication, because in the worst-case scenario, only one person at a time can use the cryptographic token. Passwords can be guessed and can be exposed to other users, so in the worst-case scenario an infinite number of people could attempt to gain unauthorized access when resources are protected using password-only authentication.
If you store the secret private key in a file, the key is usually encrypted by a password. The problem with this approach is that the encrypted key is exposed to decryption attacks or spyware/malware running on the client machine. Unlike when using a cryptographic device, the file cannot erase itself automatically after several failed decryption attempts.
What is PKCS#11?
This standard specifies an API, called Cryptoki, to devices which hold cryptographic information and perform cryptographic functions. Cryptoki, pronounced «crypto-key» and short for cryptographic token interface, follows a simple object-based approach, addressing the goals of technology independence (any kind of device) and resource sharing (multiple applications accessing multiple devices), presenting to applications a common, logical view of the device called a cryptographic token.
Finding PKCS#11 provider library
The first thing you need to do is to find the provider library, it should be installed with the device drivers. Each vendor has its own library. For example, the OpenSC PKCS#11 provider is located at /usr/lib/pkcs11/opensc-pkcs11.so on Unix or at opensc-pkcs11.dll on Windows.
How to configure cryptographic token
You should follow an enrollment procedure:
A configured token is a token that has a private key object and a certificate object, where both share the same id and label attributes.
A simple enrollment utility is Easy-RSA 2.0 which is part of OpenVPN 2.1 series. Follow the instructions specified in the README file, and then use the pkitool in order to enroll.
Initialize a token using the following command:
Enroll a certificate using the following command:
How to modify an OpenVPN configuration to make use of cryptographic tokens
You should have OpenVPN 2.1 or above in order to use the PKCS#11 features. You can grab the latest beta from http://openvpn.net/download.html.
Determine the correct slot
Each PKCS#11 provider can support multiple devices, one in each slot. In order to view the slot list you can use the following command:
You can use the output of this command in order to specify the requested slot, for example you can use the pkcs11-slot-type id, pkcs11-slot 1 options or you can use pkcs11-slot-type name, pkcs-slot «My reader 01 00» in order to select the second slot. You can also select a slot based on the token name, for example pkcs11-slot-type label, pkcs11-slot «Token1» options will select the slot where Token1 is located.
Determine the correct object
Each PKCS#11 token can contain several objects. Each object has two distinctive attributes id and label. In order to view the token contents you can use the following command:
Reference to this object can be made by:
Using OpenVPN with PKCS#11
A typical set of OpenVPN options for PKCS#11
This will select the slot where «Token1» is located, select a certificate and private key based on the label «AUTH000-20050705B436961C5E5F6D2B».
Advanced OpenVPN options for PKCS#11
This will load two providers into OpenVPN, search for the slot where «Token1» is located, select a certificate and private key based on the label «AUTH000-20050705B436961C5E5F6D2B», and use the management interface in order to query passwords. The daemon will resume into hold state on the event when token cannot be accessed. The token will be used for 300 seconds after which the password will be re-queried.
PKCS#11 implementation considerations
Many PKCS#11 providers make use of threads, in order to avoid problems caused by implementation of LinuxThreads (setuid, chroot), it is highly recommend to upgrade to Native POSIX Thread Library (NPTL) enabled glibc if you intend to use PKCS#11.
OpenSC PKCS#11 provider
OpenSC PKCS#11 provider is located at /usr/lib/pkcs11/opensc-pkcs11.so on Unix or at opensc-pkcs11.dll on Windows.
OpenSC PKCS#11 provider does not report private key attributes correctly. In order to workaround this issue you should specify the pkcs11-sign-mode sign option.
Difference between PKCS#11 and Microsoft Cryptographic API (CryptoAPI)
PKCS#11 is a free, cross-platform vendor independent standard. CryptoAPI is a Microsoft specific API. Most smart card vendors provide support for both interfaces. In the Windows environment, the user should select which interface to use.
The current implementation of OpenVPN that uses the MS CryptoAPI (cryptoapicert option) works well as long as you don’t run OpenVPN as a service. If you wish to run OpenVPN in an administrative environment using a service, the implementation will not work with most smart cards because of the following reasons:
Using the PKCS#11 interface, you can use smart cards with OpenVPN in any implementation, since PKCS#11 does not access Microsoft stores and does not necessarily require direct interaction with the end-user.
Routing all client traffic (including web-traffic) through the VPN
Overview
By default, when an OpenVPN client is active, only network traffic to and from the OpenVPN server site will pass over the VPN. General web browsing, for example, will be accomplished with direct connections that bypass the VPN.
Implementation
Add the following directive to the server configuration file:
If your VPN setup is over a wireless network, where all clients and the server are on the same wireless subnet, add the local flag:
Pushing the redirect-gateway option to clients will cause all IP network traffic originating on client machines to pass through the OpenVPN server. The server will need to be configured to deal with this traffic somehow, such as by NATing it to the internet, or routing it through the server site’s HTTP proxy.
On Linux, you could use a command such as this to NAT the VPN client traffic to the internet:
This command assumes that the VPN subnet is 10.8.0.0/24 (taken from the server directive in the OpenVPN server configuration) and that the local ethernet interface is eth0.
When redirect-gateway is used, OpenVPN clients will route DNS queries through the VPN, and the VPN server will need handle them. This can be accomplished by pushing a DNS server address to connecting clients which will replace their normal DNS server settings during the time that the VPN is active. For example:
will configure Windows clients (or non-Windows clients with some extra server-side scripting) to use 10.8.0.1 as their DNS server. Any address which is reachable from clients may be used as the DNS server address.
Caveats
Redirecting all network traffic through the VPN is not entirely a problem-free proposition. Here are some typical gotchas to be aware of:
For more information on the mechanics of the redirect-gateway directive, see the manual page.
Running an OpenVPN server on a dynamic IP address
While OpenVPN clients can easily access the server via a dynamic IP address without any special configuration, things get more interesting when the server itself is on a dynamic address. While OpenVPN has no trouble handling the situation of a dynamic server, some extra configuration is required.
The first step is to get a dynamic DNS address which can be configured to «follow» the server every time the server’s IP address changes. There are several dynamic DNS service providers available, such as dyndns.org.
The next step is to set up a mechanism so that every time the server’s IP address changes, the dynamic DNS name will be quickly updated with the new IP address, allowing clients to find the server at its new IP address. There are two basic ways to accomplish this:
Use a NAT router appliance with dynamic DNS support (such as the Linksys BEFSR41). Most of the inexpensive NAT router appliances that are widely available have the capability to update a dynamic DNS name every time a new DHCP lease is obtained from the ISP. This setup is ideal when the OpenVPN server box is a single-NIC machine inside the firewall.
Use a dynamic DNS client application such as ddclient to update the dynamic DNS address whenever the server IP address changes. This setup is ideal when the machine running OpenVPN has multiple NICs and is acting as a site-wide firewall/gateway. To implement this setup, you need to set up a script to be run by your DHCP client software every time an IP address change occurs. This script should (a) run ddclient to notify your dynamic DNS provider of your new IP address and (b) restart the OpenVPN server daemon.
The OpenVPN client by default will sense when the server’s IP address has changed, if the client configuration is using a remote directive which references a dynamic DNS name. The usual chain of events is that (a) the OpenVPN client fails to receive timely keepalive messages from the server’s old IP address, triggering a restart, and (b) the restart causes the DNS name in the remote directive to be re-resolved, allowing the client to reconnect to the server at its new IP address.
More information can be found in the FAQ.
Connecting to an OpenVPN server via an HTTP proxy.
OpenVPN supports connections through an HTTP proxy, with the following authentication modes:
First of all, HTTP proxy usage requires that you use TCP as the tunnel carrier protocol. So add the following to both client and server configurations:
Make sure that any proto udp lines in the config files are deleted.
Next, add the http-proxy directive to the client configuration file (see the manual page for a full description of this directive).
For example, suppose you have an HTTP proxy server on the client LAN at 192.168.4.1, which is listening for connections on port 1080. Add this to the client config:
Suppose the HTTP proxy requires Basic authentication:
Suppose the HTTP proxy requires NTLM authentication:
The two authentication examples above will cause OpenVPN to prompt for a username/password from standard input. If you would instead like to place these credentials in a file, replace stdin with a filename, and place the username on line 1 of this file and the password on line 2.
Connecting to a Samba share over OpenVPN
This example is intended show how OpenVPN clients can connect to a Samba share over a routed dev tun tunnel. If you are ethernet bridging (dev tap), you probably don’t need to follow these instructions, as OpenVPN clients should see server-side machines in their network neighborhood.
For this example, we will assume that:
If the Samba and OpenVPN servers are running on different machines, make sure you’ve followed the section on expanding the scope of the VPN to include additional machines.
Next, edit your Samba configuration file (smb.conf). Make sure the hosts allow directive will permit OpenVPN clients coming from the 10.8.0.0/24 subnet to connect. For example:
If you are running the Samba and OpenVPN servers on the same machine, you may want to edit the interfaces directive in the smb.conf file to also listen on the TUN interface subnet of 10.8.0.0/24:
If you are running the Samba and OpenVPN servers on the same machine, connect from an OpenVPN client to a Samba share using the folder name:
If the Samba and OpenVPN servers are on different machines, use folder name:
For example, from a command prompt window:
Implementing a load-balancing/failover configuration
Client
The OpenVPN client configuration can refer to multiple servers for load balancing and failover. For example:
will direct the OpenVPN client to attempt a connection with server1, server2, and server3 in that order. If an existing connection is broken, the OpenVPN client will retry the most recently connected server, and if that fails, will move on to the next server in the list. You can also direct the OpenVPN client to randomize its server list on startup, so that the client load will be probabilistically spread across the server pool.
If you would also like DNS resolution failures to cause the OpenVPN client to move to the next server in the list, add the following:
The 60 parameter tells the OpenVPN client to try resolving each remote DNS name for 60 seconds before moving on to the next server in the list.
The server list can also refer to multiple OpenVPN server daemons running on the same machine, each listening for connections on a different port, for example:
If your servers are multi-processor machines, running multiple OpenVPN daemons on each server can be advantageous from a performance standpoint.
OpenVPN also supports the remote directive referring to a DNS name which has multiple A records in the zone configuration for the domain. In this case, the OpenVPN client will randomly choose one of the A records every time the domain is resolved.
Server
The simplest approach to a load-balanced/failover configuration on the server is to use equivalent configuration files on each server in the cluster, except use a different virtual IP address pool for each server. For example:
Hardening OpenVPN Security
One of the often-repeated maxims of network security is that one should never place so much trust in a single security component that its failure causes a catastrophic security breach. OpenVPN provides several mechanisms to add additional security layers to hedge against such an outcome.
tls-auth
The tls-auth directive adds an additional HMAC signature to all SSL/TLS handshake packets for integrity verification. Any UDP packet not bearing the correct HMAC signature can be dropped without further processing. The tls-auth HMAC signature provides an additional level of security above and beyond that provided by SSL/TLS. It can protect against:
Using tls-auth requires that you generate a shared-secret key that is used in addition to the standard RSA certificate/key:
This command will generate an OpenVPN static key and write it to the file ta.key. This key should be copied over a pre-existing secure channel to the server and all client machines. It can be placed in the same directory as the RSA .key and .crt files.
In the server configuration, add:
In the client configuration, add:
proto udp
While OpenVPN allows either the TCP or UDP protocol to be used as the VPN carrier connection, the UDP protocol will provide better protection against DoS attacks and port scanning than TCP:
user/group (non-Windows only)
OpenVPN has been very carefully designed to allow root privileges to be dropped after initialization, and this feature should always be used on Linux/BSD/Solaris. Without root privileges, a running OpenVPN server daemon provides a far less enticing target to an attacker.
chroot (non-Windows only)
The chroot directive allows you to lock the OpenVPN daemon into a so-called chroot jail, where the daemon would not be able to access any part of the host system’s filesystem except for the specific directory given as a parameter to the directive. For example,
would cause the OpenVPN daemon to cd into the jail subdirectory on initialization, and would then reorient its root filesystem to this directory so that it would be impossible thereafter for the daemon to access any files outside of jail and its subdirectory tree. This is important from a security perspective, because even if an attacker were able to compromise the server with a code insertion exploit, the exploit would be locked out of most of the server’s filesystem.
Caveats: because chroot reorients the filesystem (from the perspective of the daemon only), it is necessary to place any files which OpenVPN might need after initialization in the jail directory, such as:
Larger RSA keys
The RSA key size is controlled by the KEY_SIZE variable in the easy-rsa/vars file, which must be set before any keys are generated. Currently set to 1024 by default, this value can reasonably be increased to 2048 with no negative impact on VPN tunnel performance, except for a slightly slower SSL/TLS renegotiation handshake which occurs once per client per hour, and a much slower one-time Diffie Hellman parameters generation process using the easy-rsa/build-dh script.
Larger symmetric keys
By default OpenVPN uses Blowfish, a 128 bit symmetrical cipher.
OpenVPN automatically supports any cipher which is supported by the OpenSSL library, and as such can support ciphers which use large key sizes. For example, the 256-bit version of AES (Advanced Encryption Standard) can be used by adding the following to both server and client configuration files:
Keep the root key (ca.key) on a standalone machine without a network connection
One of the security benefits of using an X509 PKI (as OpenVPN does) is that the root CA key (ca.key) need not be present on the OpenVPN server machine. In a high security environment, you might want to specially designate a machine for key signing purposes, keep the machine well-protected physically, and disconnect it from all networks. Floppy disks can be used to move key files back and forth, as necessary. Such measures make it extremely difficult for an attacker to steal the root key, short of physical theft of the key signing machine.
Revoking Certificates
Revoking a certificate means to invalidate a previously signed certificate so that it can no longer be used for authentication purposes.
Typical reasons for wanting to revoke a certificate include:
Example
As an example, we will revoke the client2 certificate, which we generated above in the «key generation» section of the HOWTO.
First open up a shell or command prompt window and cd to the easy-rsa directory as you did in the «key generation» section above. On Linux/BSD/Unix:
You should see output similar to this:
Note the «error 23» in the last line. That is what you want to see, as it indicates that a certificate verification of the revoked certificate failed.
The revoke-full script will generate a CRL (certificate revocation list) file called crl.pem in the keys subdirectory. The file should be copied to a directory where the OpenVPN server can access it, then CRL verification should be enabled in the server configuration:
Now all connecting clients will have their client certificates verified against the CRL, and any positive match will result in the connection being dropped.
CRL Notes
When the crl-verify option is used in OpenVPN, the CRL file will be re-read any time a new client connects or an existing client renegotiates the SSL/TLS connection (by default once per hour). This means that you can update the CRL file while the OpenVPN server daemon is running, and have the new CRL take effect immediately for newly connecting clients. If the client whose certificate you are revoking is already connected, you can restart the server via a signal (SIGUSR1 or SIGHUP) and flush all clients, or you can telnet to the management interface and explicitly kill the specific client instance object on the server without disturbing other clients.
While the crl-verify directive can be used on both the OpenVPN server and clients, it is generally unnecessary to distribute a CRL file to clients unless a server certificate has been revoked. Clients don’t need to know about other client certificates which have been revoked because clients shouldn’t be accepting direct connections from other clients in the first place.
The CRL file is not secret, and should be made world-readable so that the OpenVPN daemon can read it after root privileges have been dropped.
If you are using the chroot directive, make sure to put a copy of the CRL file in the chroot directory, since unlike most other files which OpenVPN reads, the CRL file will be read after the chroot call is executed, not before.
A common reason why certificates need to be revoked is that the user encrypts their private key with a password, then forgets the password. By revoking the original certificate, it is possible to generate a new certificate/key pair with the user’s original common name.
Important Note on possible «Man-in-the-Middle» attack if clients do not verify the certificate of the server they are connecting to.
To avoid a possible Man-in-the-Middle attack where an authorized client tries to connect to another client by impersonating the server, make sure to enforce some kind of server certificate verification by clients. There are currently five different ways of accomplishing this, listed in the order of preference:
[OpenVPN 2.1 and above] Build your server certificates with specific key usage and extended key usage. The RFC3280 determine that the following attributes should be provided for TLS connections:
Mode | Key usage | Extended key usage |
---|---|---|
Client | digitalSignature | TLS Web Client Authentication |
keyAgreement | ||
digitalSignature, keyAgreement | ||
Server | digitalSignature, keyEncipherment | TLS Web Server Authentication |
digitalSignature, keyAgreement |
You can build your server certificates with the build-key-server script (see the easy-rsa documentation for more info). This will designate the certificate as a server-only certificate by setting the right attributes. Now add the following line to your client configuration:
[OpenVPN 2.0 and below] Build your server certificates with the build-key-server script (see the easy-rsa documentation for more info). This will designate the certificate as a server-only certificate by setting nsCertType=server. Now add the following line to your client configuration:
This will block clients from connecting to any server which lacks the nsCertType=server designation in its certificate, even if the certificate has been signed by the ca file in the OpenVPN configuration file.
Use the tls-remote directive on the client to accept/reject the server connection based on the common name of the server certificate.
Use a tls-verify script or plugin to accept/reject the server connection based on a custom test of the server certificate’s embedded X509 subject details.
Sign server certificates with one CA and client certificates with a different CA. The client configuration ca directive should reference the server-signing CA file, while the server configuration ca directive should reference the client-signing CA file.
Sample OpenVPN 2.0 configuration files
sample-config-files/server.conf
sample-config-files/client.conf
Настройка OpenVPN клиента
В данной инструкции подробно описан процесс настройки клиента OpenVPN на примере операционных систем Windows и Linux. Также, с ее помощью можно настроить скиента на Android.
Установка
Windows
Заходим на официальную страницу загрузки openvpn и скачиваем клиента для нужной Windows:
Запускаем скачанный файл и устанавливаем программу, нажимая «Далее».
Linux CentOS
Устанавливаем репозиторий EPEL:
yum install epel-release
yum install openvpn
Linux Ubuntu
apt-get install openvpn
Android
Настройка
После установки программы конфигурационный файл не создается автоматически и его нужно создать вручную.
В системах Windows создаем файл config.ovpn в папке %programfiles%\OpenVPN\config.
* имя файла может быть любым, расширение должно быть .ovpn.
Для создания конфигурационного файла в Linux выполняем команду:
* чтобы служба openvpn автоматически выполняла соединение, необходимо, чтобы конфигурационный файл назывался client.conf.
Пример конфигурационного файла
client
dev tun
proto udp
remote 192.168.0.15 443
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client.crt
key client.key
dh dh2048.pem
tls-client
tls-auth ta.key 1
float
keepalive 10 120
comp-lzo
verb 0
Параметры конфигурационного файла
Параметр | Значения | Описание |
---|---|---|
client | Строка говорит о том, что конфигурационный файл описывает клиентское подключение (программа сама устанавливает соединение, а не ждет, как сервер). | |
dev | tap или tun | Выбор виртуального сетевого драйвера. TUN — сетевой уровень модели OSI, оперирует IP-пакетами. TAP — эмулирует Ethernet устройство и работает на канальном уровне модели OSI, оперируя кадрами Ethernet. Настраивая OpenVPN клиента, в большинстве случаев, необходимо выбирать tun. TAP необходимо использовать для работы определенных сервисов, например DHCP. |
dev-node | любая строка | Параметр используется в системах Windows в случаях, если имеется несколько сетевых интерфейсов. Значение этого параметра должно содержать название сетевого подключения, через который должен работать OpenVPN. |
proto | udp или tcp | Указывает, какой протокол использовать для передачи данных. В большинстве случаев, лучше использовать UDP, так как данный протокол создает меньше нагрузки на сеть. |
remote | VPN-сервер и порт | Задает сервер, к которому должен подключаться клиент, а также сетевой порт (по умолчанию 1194), на котором OpenVPN принимает запросы. Можно указать несколько строк. |
remote-random | Если указано несколько строк remote, данный параметр говорит, что необходимо подключаться к удаленным серверам в случайном порядке. | |
resolv-retry | количество секунд или infinite | Используется в тех случаях, когда в качестве сервера указано доменное имя. Параметр задает время в секундах для повторного переподключения, если не удалось узнать имя сервера. infinite — держать связь с сервером постоянно. |
nobind | Клиент использует динамический порт для подключения. | |
user | учетная запись | Задает определенного пользователя для работы клиента (только для UNIX-систем). |
group | группа | Задает определенную группу для работы клиента (только для UNIX-систем). |
persist-key | Не перечитывает ключи при перезагрузке сервиса OpenVPN. | |
persist-tun | Не перечитывает параметры туннеля при перезагрузке сервиса OpenVPN. | |
http-proxy | сервер прокси и порт | Использовать прокси-сервер для подключения. |
http-proxy-retry | Переподключаться к прокси-серверу, если связь была разорвана. | |
http-proxy-timeout | количество секунд | Время, через которое выполнять попытки переподключения к прокси-серверу. |
mute-replay-warnings | Параметр стоит задавать при использовании беспроводного соединения. Он отключит дублирование предупреждений пакетов. | |
ca | пут к сертификату | Корневой сертификат удостоверяющего центра. Генерируем на сервере. |
cert | пут к сертификату | Открытый ключ клиента. Генерируем на сервере. |
key | пут к сертификату | Закрытый ключ клиента. Генерируем на сервере. |
dh | пут к сертификату | Ключ с алгоритмом Diffie-Hellman (Диффи-Хеллмана). |
remote-cert-tls | сервер | Исключает возможность mitm атаки, включая верификацию сертификата сервера. |
tls-client | Указание на то, что это клиент TLS. | |
tls-auth | ta.key 1 | Дополнительный уровень аутентификации посредством ключа TLS. |
float | Удаленный хост может менять IP-адрес в процессе соединения, при этом последнее не будет разорвано. | |
keepalive | секунд1 секунд2 | Пинговать каждые секунд1 сервер и если в течение секунд2 не будут получены ответные пакеты, перезапустить подключение. |
cipher | алгоритм | Указывает алгоритм шифрования. Примеры: AES-256-CBC, AES-128-CBC, BF-CBC, DES-EDE3-CBC. |
comp-lzo | Использовать сжатие. | |
verb | число от 0 до 9 | Уровень детализации лога. 0 отключает отладочную информацию. |
mute | число | Указывает сколько лог-сообщений может отображаться для каждой категории события. |
auth-user-pass | ничего или путь к файлу | Говорит клиенту, что необходима аутентификация. Если не указан путь к файлу, клиент выкинет окно для авторизации, иначе прочитает данные из файла. |
ipchange | команда или путь к скрипту | Выполняет команду при смене IP. |
connect-retry | секунд | Переподключиться к серверу через указанное количество секунд, если соединение было разорвано. |
connect-retry-max | число | Сколько раз повторять соединение, если оно было разорвано. |
shaper | байт | Задает максимальную скорость передачи данных для исходящего трафика. |
tun-mtu | число | Задает MTU. |
status | путь к файлу | Путь к фалу хранения статуса. |
log | путь к файлу | Путь к лог-файлу. |
askpass | путь к файлу | Путь к файлу с паролем для приватного ключа (private key password). |
Сертификаты
Клиентские сертификаты генерируются на стороне сервера. Процедура следующая.