Настройка OpenVPN на FreeBSD: различия между версиями

Материал из Bas Wiki
Перейти к навигации Перейти к поиску
Нет описания правки
 
(не показаны 43 промежуточные версии этого же участника)
Строка 1: Строка 1:
Установка и настройка производилась на хостинге [https://www.digitalocean.com DigitalOcean] с минимальной конфигурацией (память 512 MB / диск 10 GB) и под управлением операционной системы [https://www.freebsd.org FreeBSD] 13.2.
Установка и настройка производилась на хостинге [https://www.digitalocean.com DigitalOcean] с минимальной конфигурацией (память 512 MB / диск 10 GB) и под управлением операционной системы [https://www.freebsd.org FreeBSD] 13.2.


===== Установка =====
__TOC__
 
== Установка ==
Производим установку пакета <code>openvpn</code> с помощью пакетного менеджера <code>pkg</code>:
Производим установку пакета <code>openvpn</code> с помощью пакетного менеджера <code>pkg</code>:
<pre>pkg install openvpn</pre>
<pre>pkg install openvpn</pre>
Строка 19: Строка 21:
* Указать имя конфига через параметр в <code>rc.conf</code>:
* Указать имя конфига через параметр в <code>rc.conf</code>:
<pre>
<pre>
openvpn_configfile="/usr/local/etc/openvpn/openvpn.conf"
sysrc openvpn_configfile="/usr/local/etc/openvpn/openvpn.conf"
</pre>
 
Не забываем добавить строку для старта <code>openvpn</code> и указываем название интерфейса:
<pre>
sysrc openvpn_enable="YES"
sysrc openvpn_if="tun"
</pre>
 
 
== Настройка ключей и сертификатов ==
 
Для начала необходимо провести инициализацию пакета:
<pre>
cd /usr/local/etc/openvpn
easyrsa init-pki
</pre>
 
Редактируем файл с переменными:
<pre>
vi /usr/local/etc/openvpn/pki
</pre>
 
Нас интересует блок с настройками сертификата. Необходимо раскомментировать эти переменные и настроить под себя:
<pre>
set_var EASYRSA_REQ_COUNTRY    "DE"
set_var EASYRSA_REQ_PROVINCE  "Frankfurt"
set_var EASYRSA_REQ_CITY      "Frankfurt"
set_var EASYRSA_REQ_ORG        "Applied Internet Projects"
set_var EASYRSA_REQ_EMAIL      "admin@bas.gg"
set_var EASYRSA_REQ_OU        "vpn2.bas.gg"
</pre>
</pre>


===== Настройка ключей и сертификатов =====
=== Сертификат CA ===
Генерируем корневой сертификат. Указываем имя сервера:
<pre>
root@do:/usr/local/etc/openvpn# easyrsa build-ca nopass


2
* Using SSL: openssl OpenSSL 1.1.1t-freebsd  7 Feb 2023
 
* Using Easy-RSA configuration: /usr/local/etc/openvpn/pki/vars
 
..........................................+++++
................................+++++
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:vpn2.bas.gg
</pre>
 
 
=== Сертификат сервера ===
 
Генерируем серверный сертификат.<br>
Не забываем написать <code>yes</code>:
<pre>
 
root@do:/usr/local/etc/openvpn# easyrsa build-server-full openvpn-server nopass
 
* Using SSL: openssl OpenSSL 1.1.1t-freebsd  7 Feb 2023
 
* Using Easy-RSA configuration: /usr/local/etc/openvpn/pki/vars
Generating a RSA private key
...........+++++
...................................................+++++
writing new private key to '/usr/local/etc/openvpn/pki/3f0262d7/temp.b7344ff0'
-----
 
Notice
------
Keypair and certificate request completed. Your files are:
req: /usr/local/etc/openvpn/pki/reqs/openvpn-server.req
key: /usr/local/etc/openvpn/pki/private/openvpn-server.key
 
You are about to sign the following certificate.
Please check over the details shown below for accuracy. Note that this request
has not been cryptographically verified. Please be sure it came from a trusted
source or that you have verified the request checksum with the sender.
 
Request subject, to be signed as a server certificate for 825 days:
 
subject=
    commonName                = openvpn-server
 
 
Type the word 'yes' to continue, or any other input to abort.
  Confirm request details: yes
</pre>
 
 
=== Ключ Diffie Hellman ===
 
Генерируем ключ Diffie Hellman:
<pre>
easyrsa gen-dh
</pre>
 
 
=== Ключ безопасности ===
 
Переходим в папку с сертификатами и ключами и генерируем ключ для улучшения безопасности:
<pre>
cd /usr/local/etc/openvpn/pki
openvpn --genkey secret ta.key
</pre>
 
== Настройка OpenVPN ==
 
Редактируем файл <code>/usr/local/etc/openvpn/server.conf</code> (или <code>/usr/local/etc/openvpn/openvpn.conf</code>, если вы переименовывали конфиг).<br>
Находим настройки для путей сертификатов и ключей и исправляем их. В моём случае мне достаточно заменить папку <code>keys</code> на <code>pki</code>:
<pre>
# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key).  Each client
# and the server must have their own cert and
# key file.  The server and all clients will
# use the same ca file.
#
# See the "easy-rsa" directory for a series
# of scripts for generating RSA certificates
# and private keys.  Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see "pkcs12" directive in man page).
ca /usr/local/etc/openvpn/pki/ca.crt
cert /usr/local/etc/openvpn/pki/issued/openvpn-server.crt
key /usr/local/etc/openvpn/pki/private/openvpn-server.key  # This file should be kept secret
 
# Diffie hellman parameters.
# Generate your own with:
#  openssl dhparam -out dh2048.pem 2048
dh /usr/local/etc/openvpn/pki/dh.pem
</pre>
 
<pre>
# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
#  openvpn --genkey tls-auth ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
tls-auth /usr/local/etc/openvpn/pki/ta.key 0 # This file is secret
</pre>
 
== Запуск OpenVPN ==
 
Запускаем сервис стандартным способом:
<pre>
service openvpn start
</pre>
 
 
== Создание клиентского сертификата ==
 
Для того, чтобы мы могли подключаться к серверу необходимо создать файл для пользователя.<br>
Не забываем написать <code>yes</code>:
 
<pre>
cd /usr/local/etc/openvpn
easyrsa build-client-full bas nopass
</pre>


===== Настройка openvpn =====


3


[[Category:FreeBSD]]
[[Category:FreeBSD]]
[[Category:VPN]]
[[Category:VPN]]
[[Category:OpenVPN]]
[[Category:OpenVPN]]

Текущая версия от 10:46, 18 июня 2023

Установка и настройка производилась на хостинге DigitalOcean с минимальной конфигурацией (память 512 MB / диск 10 GB) и под управлением операционной системы FreeBSD 13.2.

Установка

Производим установку пакета openvpn с помощью пакетного менеджера pkg:

pkg install openvpn

Автоматически папка с конфигами не создаётся, поэтому создаём её вручную:

mkdir /usr/local/etc/openvpn

Копируем шаблон конфига, который находится в /usr/local/share/examples/openvpn/sample-config-files в рабочую папку:

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

По умолчанию openvpn ищет конфиг с именем openvpn.conf, поэтому есть 2 опции:

  • Переименовать конфиг:
mv /usr/local/etc/openvpn/server.conf /usr/local/etc/openvpn/openvpn.conf
  • Указать имя конфига через параметр в rc.conf:
sysrc openvpn_configfile="/usr/local/etc/openvpn/openvpn.conf"

Не забываем добавить строку для старта openvpn и указываем название интерфейса:

sysrc openvpn_enable="YES"
sysrc openvpn_if="tun"


Настройка ключей и сертификатов

Для начала необходимо провести инициализацию пакета:

cd /usr/local/etc/openvpn
easyrsa init-pki

Редактируем файл с переменными:

vi /usr/local/etc/openvpn/pki

Нас интересует блок с настройками сертификата. Необходимо раскомментировать эти переменные и настроить под себя:

set_var EASYRSA_REQ_COUNTRY    "DE"
set_var EASYRSA_REQ_PROVINCE   "Frankfurt"
set_var EASYRSA_REQ_CITY       "Frankfurt"
set_var EASYRSA_REQ_ORG        "Applied Internet Projects"
set_var EASYRSA_REQ_EMAIL      "admin@bas.gg"
set_var EASYRSA_REQ_OU         "vpn2.bas.gg"

Сертификат CA

Генерируем корневой сертификат. Указываем имя сервера:

root@do:/usr/local/etc/openvpn# easyrsa build-ca nopass

* Using SSL: openssl OpenSSL 1.1.1t-freebsd  7 Feb 2023

* Using Easy-RSA configuration: /usr/local/etc/openvpn/pki/vars

..........................................+++++
................................+++++
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:vpn2.bas.gg


Сертификат сервера

Генерируем серверный сертификат.
Не забываем написать yes:


root@do:/usr/local/etc/openvpn# easyrsa build-server-full openvpn-server nopass

* Using SSL: openssl OpenSSL 1.1.1t-freebsd  7 Feb 2023

* Using Easy-RSA configuration: /usr/local/etc/openvpn/pki/vars
Generating a RSA private key
...........+++++
...................................................+++++
writing new private key to '/usr/local/etc/openvpn/pki/3f0262d7/temp.b7344ff0'
-----

Notice
------
Keypair and certificate request completed. Your files are:
req: /usr/local/etc/openvpn/pki/reqs/openvpn-server.req
key: /usr/local/etc/openvpn/pki/private/openvpn-server.key

You are about to sign the following certificate.
Please check over the details shown below for accuracy. Note that this request
has not been cryptographically verified. Please be sure it came from a trusted
source or that you have verified the request checksum with the sender.

Request subject, to be signed as a server certificate for 825 days:

subject=
    commonName                = openvpn-server


Type the word 'yes' to continue, or any other input to abort.
  Confirm request details: yes


Ключ Diffie Hellman

Генерируем ключ Diffie Hellman:

easyrsa gen-dh


Ключ безопасности

Переходим в папку с сертификатами и ключами и генерируем ключ для улучшения безопасности:

cd /usr/local/etc/openvpn/pki 
openvpn --genkey secret ta.key

Настройка OpenVPN

Редактируем файл /usr/local/etc/openvpn/server.conf (или /usr/local/etc/openvpn/openvpn.conf, если вы переименовывали конфиг).
Находим настройки для путей сертификатов и ключей и исправляем их. В моём случае мне достаточно заменить папку keys на pki:

# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key).  Each client
# and the server must have their own cert and
# key file.  The server and all clients will
# use the same ca file.
#
# See the "easy-rsa" directory for a series
# of scripts for generating RSA certificates
# and private keys.  Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see "pkcs12" directive in man page).
ca /usr/local/etc/openvpn/pki/ca.crt
cert /usr/local/etc/openvpn/pki/issued/openvpn-server.crt
key /usr/local/etc/openvpn/pki/private/openvpn-server.key  # This file should be kept secret

# Diffie hellman parameters.
# Generate your own with:
#   openssl dhparam -out dh2048.pem 2048
dh /usr/local/etc/openvpn/pki/dh.pem
# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
#   openvpn --genkey tls-auth ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
tls-auth /usr/local/etc/openvpn/pki/ta.key 0 # This file is secret

Запуск OpenVPN

Запускаем сервис стандартным способом:

service openvpn start


Создание клиентского сертификата

Для того, чтобы мы могли подключаться к серверу необходимо создать файл для пользователя.
Не забываем написать yes:

cd /usr/local/etc/openvpn
easyrsa build-client-full bas nopass