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

Материал из Bas Wiki
Перейти к навигации Перейти к поиску
Нет описания правки
Строка 75: Строка 75:
</pre>
</pre>


Запоминаем, где расположен файл сертификата. Он нам пригодится для настройки openvpn:
<pre>
Notice
------
CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
/usr/local/etc/openvpn/pki/ca.crt
</pre>


=== Сертификат сервера ===
=== Сертификат сервера ===
Строка 122: Строка 114:
</pre>
</pre>


Запоминаем пути к файлу сертификата:
<pre>
Using configuration from /usr/local/etc/openvpn/pki/3f0262d7/temp.83decd23
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'openvpn-server'
Certificate is to be certified until Aug 23 12:39:23 2025 GMT (825 days)
Write out database with 1 new entries
Data Base Updated
Notice
------
Certificate created at:
* /usr/local/etc/openvpn/pki/issued/openvpn-server.crt
Notice
------
Inline file created:
* /usr/local/etc/openvpn/pki/inline/openvpn-server.inline
</pre>


=== Ключ Diffie Hellman ===
=== Ключ Diffie Hellman ===
Строка 152: Строка 122:
</pre>
</pre>


Запоминаем расположение сгенерированного файла:
<pre>
Notice
------
DH parameters of size 2048 created
at: /usr/local/etc/openvpn/pki/dh.pem
</pre>


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

Версия от 13:33, 21 мая 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/openvpn-server.crt
key /usr/local/etc/openvpn/pki/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