This tutorial is going to show you how to set up your own WireGuard VPN server on CentOS/RHEL. WireGuard is made specifically for the Linux kernel. It runs inside the Linux kernel and allows you to create fast, modern, and secure VPN tunnel.
This tutorial is going to show you how to run your own VPN server by installing OpenConnect VPN server on CentOS 8/RHEL 8. OpenConnect VPN server, aka ocserv, is an open-source implementation of the Cisco AnyConnnect VPN protocol, which is widely used in businesses and universities. AnyConnect is an SSL-based VPN protocol that allows individual users to connect to a remote network.
- Start WireGuard
- server
- Client
- Auto-Connect on System Startup
- Настройка VPN PPTP
- Настройка L2TP VPN
- Настройка IPsec
- Lets get started with installation :-
- Install Net-Tools :
- Now we’ll install OpenVPN on Centos 7 :
- Changing OpenVPN ports :
- Prerequisites:
- Setting Up IPsec/L2TP VPN Server in Linux
- How to Add or Remove a VPN User in Linux
- How to Upgrade Libreswan Installation in Linux
- How to Uninstall the VPN Server in Linux
- On RHEL/CentOS
- On Debian/Ubuntu
- Adding Additional VPN Clients
- Configure IP Masquerading in Firewall
- Policy Routing, Split Tunneling & VPN Kill Switch
- Policy Routing
- Split Tunneling
- VPN Kill Switch
- Wrapping Up
- Creating VPN Accounts
- Wrapping Up
- Virtual Hosting
- Generate Public/Private Keypair
- Server
- Client
- Open WireGuard Port in Firewall
- Features of OpenConnect VPN server
- Requirements
- Enable IP Forwarding on the Server
- Install OpenConnect VPN Server (ocserv) on CentOS 8
- Enable IP Forwarding in Linux Kernel
- Install Let’s Encrypt Client (Certbot) on CentOS 8 Server
- Open Ports in Firewall
- Configure IP Masquerading on the Server
- Install and Use OpenConnect VPN client on CentOS 8/Fedora Desktop
- Obtain a Trusted TLS Certificate from Let’s Encrypt
- Standalone Plugin
- Using webroot Plugin
- Apache
- Nginx
- Per-User or Per Group Configuration
- Edit OpenConnect VPN Server Configuration File
- Speed Optimization
- Troubleshooting Tips
- Install a DNS Resolver on the Server
- Troubleshooting Tips
- No Tap-Windows Adapter installed on this system
- Why Set Up Your Own VPN Server?
- Auto-Renew Let’s Encrypt Certificate
- How to Set Up VPN Relay
- Requirements
- How to Disable TLS 1. 0 and TLS 1. 1 in ocserv
- Create WireGuard Configuration File
- Server
- Client
- Configure VPN Client on iOS/Andorid
- OpenConnect GUI Client for Windows and MacOS
- Features of WireGuard VPN
- Speed
- Configure Windows Client
- Install WireGuard on CentOS/RHEL Server and Desktop
- CentOS 8/Rocky Linux 8/Alma Linux 8
- RHEL 8
- CentOS/RHEL 7
- How to Run Multiple Instances of ocserv
- If You Appreciate What We Do Here On TecMint, You Should Consider
- If You Appreciate What We Do Here On TecMint, You Should Consider
- If You Appreciate What We Do Here On TecMint, You Should Consider
Start WireGuard
server
sudo systemctl start [email protected]
If the start failed, you should check the log to find out what’s wrong.
sudo journalctl -eu [email protected]
sudo systemctl enable [email protected]
systemctl status [email protected]
Now WireGuard server is ready to accept client connections.
Client
sudo systemctl start [email protected]
If the start failed, you should check the log to find out what’s wrong.
sudo journalctl -eu [email protected]
RTNETLINK answers: Operation not supported
Enable auto-start at system boot time.
sudo systemctl enable [email protected]
Check its status:
systemctl status [email protected]
Now go to this website: http://icanhazip.com/
to check your public IP address. If everything went well, it should display your VPN server’s public IP address instead of your client computer’s public IP address.
curl https://icanhazip.com
Auto-Connect on System Startup
To make OpenConnect VPN client automatically connect to the server at boot time, we can create a systemd service unit.
sudo nano /etc/systemd/system/openconnect.service
[Unit] Description=OpenConnect VPN Client After=network-online.target Wants=network-online.target [Service] Type=simple ExecStart=/bin/bash -c '/bin/echo -n | /usr/sbin/openconnect -u --passwd-on-stdin' KillSignal=SIGINT Restart=always RestartSec=2 [Install] WantedBy=multi-user.target
Save and close the file. Then enable this service so that it will start at boot time.
sudo systemctl enable openconnect.service
Explanation of the file content:
After=network-online.target
andWants=network-online.target
make this service run after network is up.- In reality, this service can still run before network is up. We add
Restart=always
andRestartSec=2
to restart this service after 2 seconds if this service fails. - Systemd doesn’t recognize pipe redirection. So in the
ExecStart
directive, we wrap the command in single quotes and run it with the Bash shell. - Since OpenConnect VPN client will run as a systemd service, which runs in the background, there’s no need to add
-b
flag to theopenconnect
command. - The
KillSignal
directive tells Systemd to send theSIGINT
signal when thesystemctl stop openconnect
command is issued. This will perform a clean shutdown by logging the session off, and restoring DNS server settings and the Linux kernel routing table.
To start this Systemd service immediately, run
sudo systemctl start openconnect
To stop this Systemd service, run
sudo systemctl stop openconnect
В этой статье я рассмотрю на практике полный алгоритм настройки VPN сервера на примере CentOS 7.6. Мы одновременно включим и L2TP и PPTP сервер.
Для работы VPN в Linux необходимо настроить 3 слоя: IPsec, L2TP и PPP. Причем, PPP будет общий для L2TP и PPTP серверов. Настройка L2TP сложнее, чем PPTP. В ней:
- IPsec обеспечивает конфиденциальность сетевого соединения и авторизации клиента (системы)
- С L2TP туннель настроен так, что VPN трафик прозрачно проходит через IPsec
- PPP (протокол точка-точка) контролирует авторизацию пользователей
Настройка VPN PPTP
Перед началом установки непосредственно сервера я рекомендую обновить пакеты и установить Midnight Commander (mc) и VestaCP для удобства. Вместе с VestaCP поставится большая часть пакетов, поэтому часть команд ниже будут излишними, не пугайтесь. В mc удобнее редактировать конфиг файлы.
epel-release mc net-tools
Далее необходимо отключить Selinux.
Система принудительного контроля Selinux отключается правкой конфигурационного файла /etc/sysconfig/selinux.
mcedit etcsysconfigselinux
или заменяем значение командой sed:
etcsysconfigselinux etcselinuxconfig
После перезагрузки проверьте статус SELinux командой «sestatus
», Вы должны увидеть следующий вывод:
Переходим к установке PPTP VPN сервера и добавлении его в автозагрузку:
ppp pptp pptpd pptp-setup chkconfig pptpd on
Далее настройка конфигов из консоли (копируем, вставляем и жмём «Enter»). Перед началом редактирования бэкапим каждый файл.
etcpptpd.conf etcpptpd.conf.bak
cat >/etc/pptpd.conf<<EOF
option /etc/ppp/options.pptpd
logwtmp
localip 172.16.0.1
remoteip 172.16.0.10-254
EOF
В этом файле
- localip — ip адрес из выбранной вами подсети, который будет являться локальным шлюзом для клиентов VPN.
- remoteip — пул ip адресов для раздачи клиентам VPN.
Если на вашей машине несколько внешних IP адресов, то вы можете указать конкретный IP, по которому будет доступно подключение к VPN серверу. В конце файла добавьте:
Файл /etc/ppp/options.pptpd
Редактирование данного файла преследует собою цель — указание DNS серверов.
В примере ниже гугловские, можно заменить на свои.
ms-dns 8.8.8.8 ms-dns 8.8.4.4
Также добавляем метод mschap2: require-mschap-v2
etcpppoptions.pptpd etcpppoptions.pptpd.bak
cat >/etc/ppp/options.pptpd<<EOF
name pptpd
refuse-pap
refuse-chap
refuse-mschap
require-mschap-v2
require-mppe-128
proxyarp
lock
nobsdcomp
novj
novjccomp
nologfd
ms-dns 8.8.8.8
ms-dns 8.8.4.4
EOF
etcpppchap-secrets etcpppchap-secrets.bak
Устанавливаем права на файл паролей, чтобы только root его мог читать:
etcpppchap-secrets
Редактирование данного файла преследует собою цель — изменение значения «0» на «1» net.ipv4.ip_forward = 1.
etcsysctl.conf etcsysctl.conf.bak
cat >/etc/sysctl.conf<<EOF
net.core.wmem_max = 12582912
net.core.rmem_max = 12582912
net.ipv4.tcp_rmem = 10240 87380 12582912
net.ipv4.tcp_wmem = 10240 87380 12582912
net.core.wmem_max = 12582912
net.core.rmem_max = 12582912
net.ipv4.tcp_rmem = 10240 87380 12582912
net.ipv4.tcp_wmem = 10240 87380 12582912
net.core.wmem_max = 12582912
net.core.rmem_max = 12582912
net.ipv4.tcp_rmem = 10240 87380 12582912
net.ipv4.tcp_wmem = 10240 87380 12582912
net.ipv4.ip_forward = 1
EOF
На этом установка и настройка VPN PPTP сервера закончена.
Осталось только «разобраться» с файерволом.
Удаляем firewalld (если не удален или не отключен):
systemctl stop firewalld systemctl disable firewalld
и вместо него ставим IPTABLES:
iptables-services iptables
Включим автозапуск iptables:
systemctl iptables +x etcrc.drc.local
Теперь процесс настройки IPTABLES подошёл к ответственному моменту — настройке конфигурации таблиц, включению маршрутизации и открытию TCP портов 1723 и 22. Необходимо добавить следующие строки в файл iptables:
mcedit etcsysconfigiptables
Cохраняем и перезапускаем всё: файерволл и сервер PPTP VPN.
service iptables save service iptables restart systemctl start pptpd
Обратите внимание, если при редактировании конфигурационного файла iptables не сохраняются настройки, а после перезагрузки файл принимает своё первоначальное значение, то для того, чтобы после редактирования файла изменения вступили в силу, необходимо перед редактированием отключить файервол iptables:
Затем отредактировать файл /etc/sysconfig/iptables, сохранить изменения
И, наконец, запустить сервиc
Обратите внимание, что eth0 — имя вашего сетевого интерфейса. Вы можете узнать его с помощью команды ifconfig. Если вам необходимо, чтобы была локальная сеть между клиентами, подключенными к VPN, добавьте следующие правила в iptables путем выполнения следующих команд из консоли или непосредственно редактируя iptables файл (кому как нравится):
iptables nat POSTROUTING ppp0 MASQUERADE iptables INPUT 172.16.0.0 ppp0 ACCEPT iptables FORWARD eth0 ACCEPT
Как видно, мы включаем маскарадинг для ppp0 и разрешаем обращаться к VPN интерфейсу клиентам из VPN сети. Обратите внимание, что 172.16.0.0/24 — локальная подсеть, которую вы себе выбрали, а ppp0 — имя pptp интерфейса.
Если вы решили не отключать firewalld и не использовать iptables, то вам потребуются следующие команды для настройки файрвола:
Проверяем, запущен ли pptp-сервер:
Проверяем, слушается ли наш порт:
listen
Дополнительная команда для проверки статуса pptpd:
Настройка L2TP VPN
Второй уровень, протокол туннелирования второго уровня (L2TP), настраивается намного проще, чем IPsec, поэтому начнем с него. L2TP абсолютно небезопасен и не должен быть доступен вне соединения IPsec. При использовании iptables, примените следующие правила, чтобы заблокировать все соединения L2TP вне ipsec:
iptables filter INPUT udp policy ipsec udp l2tp ACCEPT iptables filter INPUT udp udp l2tp REJECT icmp-port-unreachable iptables filter OUTPUT udp policy out ipsec udp l2tp ACCEPT iptables filter OUTPUT udp udp l2tp REJECT icmp-port-unreachable
Устанавливаем необходимые пакеты:
xl2tpd libreswan lsof
Бэкапим дефолтный конфиг:
etcxl2tpdxl2tpd.conf etcxl2tpdxl2tpd.conf.orig
Для использования сервера RADIUS или DHCP, оставьте отключенными опции ip range
и local ip
. Если соединение нестабильно, попробуйте добавить length bit = yes
в раздел lns default
. Чтобы не использовать PPP аутентификацию, замените require authentication = yes
на refuse authentication = yes
.
Создаем новый файл options.xl2tpd опций с таким содержимым:
mcedit /etc/ppp/options.xl2tpd
Настройка IPsec
Есть несколько вариантов и пакетов для настройки IPsec: ipsec-tools, LibreSwan (OpenSwan) и strongSwan. ipsec-tools (racoon) наименее функционален, но для тех, кто пришёл из *BSD, он может быть более близок. Однако, в отличие от *BSD, Linux не использует отдельный интерфейс для IPsec. strongSwan – это ответвление от FreeS/WAN. LibreSwan – ответвление от Openswan (который сам является ответвлением от FreeS/WAN) с сохранением его оригинальных разработчиков. Мы будем использовать именно LibreSwan, который мы уже ранее установили. Обход NAT установлен по умолчанию в файле конфигурации LibreSwan, таким образом никаких особых этапов настройки не требуется.
Желательно иметь каждую настройку VPN в своём собственном файле, что может быть сделано раскомментированием последней строки в /etc/ipsec.conf:
Основные конфигурационные файлы для это:
- /etc/ipsec.conf – определяет параметры IPSEC-соединений и параметры подключений в целом;
- /etc/ipsec.secrets – ключи и пароли для шифрования
Файл /etc/ipsec.conf разбит на разделы:
- config setup – глобальные параметры и опции
- conn %default – параметры ipsec-соединений по-умолчанию. Если в отдельных параметрах соединений не указан параметр, то используются параметры отсюда.
Например: conn SomeTunnel – раздел с параметрами соединения SomeTunnel
Файл /etc/ipsec.secrets
содержит неограниченное количество типов ключей (паролей).
Основные параметры команды ipsec, которая управляет подключениями :
- start|restart|stop;
- ipsec status|statusall — для просмотра состояния IPSEC-соединений;
- up|down|route|unroute — для управления IPSEC-соединений.
Логи хранятся в /var/log/auth.log и /var/log/daemon.log.
Создаем файл настроек с таким содержимым:
mcedit etcipsec.dl2tp-ipsec.conf
где 1.1.1.1 заменяем на ваш внешний IP.
- conn L2TP-PSK-NAT – служебное слово conn означает название соединения. После него будут параметры, которые характеризуют соединение.
- left= и right= – адреса хостов. Слова символизируют то, что хосты находятся с разных сторон. Не имеет значения, в какой из них вы впишете свой адрес, система автоматически определит, какой из адресов относится к ее интерфейсу. Поэтому на разных хостах вполне можно использовать одинаковый конфиг. Вместо адреса можно использовать ключевое слово %any в виде right=%any. Тогда можно будет подключаться с любого адреса. Так выглядит общая конфигурация, которую можно использовать:
left=%defaultroute
leftprotoport=udp/l2tp
leftid=@vpn.example.com
right=%any
rightprotoport=udp/%any
- type=tunnel – тип соединения. Может принимать значения tunnel, transport или passthrough.
- authby=secret – что будет использоваться в качестве ключа: PSK (парольное слово) или RSA (ключ)
- auto=start – опция определяет, когда включать соединение. Может принимать значения: start (автоматически стартовать), add (стартовать в ответ на инициацию от другого хоста), ignore (игнорировать соединение), manual (стартовать вручную), route (назначение мне осталось непонятно, используется крайне редко).
Ну и так как мы задали тип авторизации с помощью , то давайте запишем секретное слово в файл ..
etcipsec.ddefault.secrets
: PSK "SecretKey"
PUT_VPN_SERVER_IP %any : PSK 0x87839cfdab5f74bc211de156d2902d128bec3243
# Или используйте простой текстовый ключ вместо шестнадцатеричного:
# PUT_VPN_SERVER_IP %any : PSK "password_pass"
etcpppchap-secrets
Настроим logrotate для /var/log/xl2tpd.log
etclogrotate.dxl2tpd
Запускаем и тестируем.
systemctl ipsec systemctl xl2tpd systemctl start ipsec systemctl start xl2tpd
Можно все это проделать вручную, либо воспользоваться этим скриптом. Также можно воспользоваться другим универсальным скриптом для CentOS, Ubuntu и Debian — https://github.com/hwdsl2/setup-ipsec-vpn.
In this tutorial we’ll install OpenVPN VPN server on VPS or dedicated server. OpenVPN is an open-source software application that implements virtual private network techniques for creating secure point-to-point or site-to-site connections in routed or bridged configurations and remote access facilities.
OpenVPN can be used in OpenVZ, KVM and Dedicated environment, For Openvz virtualization type you need to do extra config like “TUN/TAP” need to enabled from backend now days this options are available directly under server management panel you can easily turn it on and off. For KVM and Dedicated server “TUN/TAP” enabling is not needed.
Lets get started with installation :-
Install Net-Tools :
yum install net-tools -y
Now we’ll install OpenVPN on Centos 7 :
rpm -i https://openvpn.net/downloads/openvpn-as-latest-CentOS7.x86_64.rpm
After running the install command it will output similar result :
[root@srv1 ~]# rpm -i https://openvpn.net/downloads/openvpn-as-latest-CentOS7.x86_64.rpm The Access Server has been successfully installed in /usr/local/openvpn_as Configuration log file has been written to /usr/local/openvpn_as/init.log Please enter "passwd openvpn" to set the initial administrative password, then login as "openvpn" to continue configuration here: https://107.154.44.444:943/admin To reconfigure manually, use the /usr/local/openvpn_as/bin/ovpn-init tool. +++++++++++++++++++++++++++++++++++++++++++++++ Access Server Web UIs are available here: Admin UI: https://107.154.44.444:943/admin Client UI: https://107.154.44.444:943/ +++++++++++++++++++++++++++++++++++++++++++++++ Beginning with OpenVPN AS 2.6.0 compression is disabled by default and on upgrades as security patch.
At this point you’ve successfully installed OpenVPN VPN server successfully now you need to run this command to change the password :
passwd openvpn
Now you can access OpenVPN GUI from web browser :
To download OpenVPN client:
Changing OpenVPN ports :
In this article, you will learn how to quickly and automatically set up your own IPsec/L2TP VPN server in CentOS/RHEL, Ubuntu, and Debian Linux distributions.
Prerequisites:
- A fresh CentOS/RHEL or Ubuntu/Debian VPS (Virtual Private Server) from any provider such as Linode.
Setting Up IPsec/L2TP VPN Server in Linux
However, if you want to use your own credentials, first you need to generate a strong password and PSK as shown.
# openssl rand -base64 10 # openssl rand -base64 16

- VPN_IPSEC_PSK – Your IPsec pre-shared key.
- VPN_USER – Your VPN username.
- VPN_PASSWORD – Your VPN password.
---------------- On CentOS/RHEL ---------------- # wget https://git.io/vpnsetup-centos -O vpnsetup.sh && VPN_IPSEC_PSK='KvLjedUkNzo5gBH72SqkOA==' VPN_USER='tecmint' VPN_PASSWORD='8DbDiPpGbcr4wQ==' sh vpnsetup.sh ---------------- On Debian and Ubuntu ---------------- # wget https://git.io/vpnsetup -O vpnsetup.sh && VPN_IPSEC_PSK='KvLjedUkNzo5gBH72SqkOA==' VPN_USER='tecmint' VPN_PASSWORD='8DbDiPpGbcr4wQ==' sudo sh vpnsetup.sh
The main packages that will be installed are bind-utils, net-tools, bison, flex, gcc, libcap-ng-devel, libcurl-devel, libselinux-devel, nspr-devel, nss-devel, pam-devel, xl2tpd, iptables-services, systemd-devel, fipscheck-devel, libevent-devel, and fail2ban(to protect SSH), and their respective dependencies. Then it downloads, compiles and installs Libreswan from source, enables and starts the necessary services.

To add the VPN connection in a mobile device such as an Android phone, go to Settings –> Network & Internet (or Wireless & Networks –> More) –> Advanced –> VPN. Select the option to add a new VPN. The VPN type should be set to IPSec Xauth PSK, then use the VPN gateway and credentials above.
How to Add or Remove a VPN User in Linux
$ wget -O add_vpn_user.sh https://raw.githubusercontent.com/hwdsl2/setup-ipsec-vpn/master/extras/add_vpn_user.sh $ sudo sh add_vpn_user.sh 'username_to_add' 'user_password'
$ wget -O del_vpn_user.sh https://raw.githubusercontent.com/hwdsl2/setup-ipsec-vpn/master/extras/del_vpn_user.sh $ sudo sh del_vpn_user.sh 'username_to_delete'
How to Upgrade Libreswan Installation in Linux
You can upgrade the Libreswan installation using the vpnupgrade.sh or vpnupgrade_centos.sh script. Make sure to edit the SWAN_VER variable to the version you want to install, within the script.
---------------- On CentOS/RHEL ---------------- # wget https://git.io/vpnupgrade-centos -O vpnupgrade.sh && sh vpnupgrade.sh ---------------- On Debian and Ubuntu ---------------- # wget https://git.io/vpnupgrade -O vpnupgrade.sh && sudo sh vpnupgrade.sh
How to Uninstall the VPN Server in Linux
On RHEL/CentOS
# yum remove xl2tpd
Then open /etc/sysconfig/iptables configuration file and remove the unneeded rules and edit /etc/sysctl.conf and /etc/rc.local file, and remove the lines after the comment # Added by hwdsl2 VPN script, in both files.
On Debian/Ubuntu
$ sudo apt-get purge xl2tpd
Next, edit /etc/iptables.rules configuration file and remove any unneeded rules. Additionally, edit /etc/iptables/rules.v4 if it exists.
Then edit /etc/sysctl.conf and /etc/rc.local files, remove the lines after the comment # Added by hwdsl2 VPN script, in both files. Do not remove exit 0 if it exists.
Optionally, you can remove certain files and directories that were created during the VPN set up.
# rm -f /etc/ipsec.conf* /etc/ipsec.secrets* /etc/ppp/chap-secrets* /etc/ppp/options.xl2tpd* /etc/pam.d/pluto /etc/sysconfig/pluto /etc/default/pluto # rm -rf /etc/ipsec.d /etc/xl2tpd
To set up a site-to-site IPSec-based VPN with Strongswan, check out our guides:
Adding Additional VPN Clients
WireGuard is designed to associate one IP address with one VPN client. To add more VPN clients, you need to create a unique private/public key pair for each client, then add each VPN client’s public key in the server’s config file (/etc/wireguard/wg0.conf
) like this:
[Interface] Address = 10.10.10.1/24 PrivateKey = UIFH+XXjJ0g0uAZJ6vPqsbb/o68SYVQdmYJpy/FlGFA= ListenPort = 51820 [Peer] PublicKey = 75VNV7HqFh+3QIT5OHZkcjWfbjx8tc6Ck62gZJT/KRA= AllowedIPs = 10.10.10.2/32 [Peer] PublicKey = YYh4/1Z/3rtl0i7cJorcinB7T4UOIzScifPNEIESFD8= AllowedIPs = 10.10.10.3/32 [Peer] PublicKey = EVstHZc6QamzPgefDGPLFEjGyedJk6SZbCJttpzcvC8= AllowedIPs = 10.10.10.4/32
Each VPN client will have a static private IP address (10.10.10.2, 10.10.10.3, 10.10.10.4, etc). Restart the WireGuard server for the changes to take effect.
sudo systemctl restart [email protected]
Then add WireGuard configuration on each VPN client as usual.
Configure IP Masquerading in Firewall
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.10.10.0/24" masquerade' sudo systemctl reload firewalld
This will hide your VPN network from the outside world. So the Internet can only see your VPN server’s IP, but can’t see your VPN client’s IP, just like your home router hides your private home network.
Now OpenConnect VPN server is ready to accept client connections.
Policy Routing, Split Tunneling & VPN Kill Switch
Now I will show you how to use policy routing, split tunneling, and VPN kill switch with WireGuard VPN. Note that it’s not recommended to use them in conjunction with each other. If you use policy routing, then you should not enable split tunneling or VPN kill switch, and vice versa.
Policy Routing
By default, all traffic on the VPN client will be routed through the VPN server. Sometimes you may want to route only a specific type of traffic, based on the transport layer protocol and the destination port. This is known as policy routing.
Policy routing is configured on the client computer, and we need to stop the VPN connection first.
sudo systemctl stop [email protected]
Then edit the client configuration file.
sudo nano /etc/wireguard/wg-client0.conf
Table = 1234 PostUp = ip rule add ipproto tcp dport 25 table 1234 PreDown = ip rule delete ipproto tcp dport 25 table 1234
Save and close the file. Then start WireGuard client again.
sudo systemctl start [email protected]
Split Tunneling
By default, all traffic on the VPN client will be routed through the VPN server. Here’s how to enable split tunneling, so only traffic to the 10.10.10.0/24
IP range will be tunneled through WireGuard VPN. This is useful when you want to build a private network for several cloud servers, because VPN clients will run on cloud servers and if you use a full VPN tunnel, then you will probably lose connection to the cloud servers.
Edit the client configuration file.
sudo nano /etc/wireguard/wg-client0.conf
AllowedIPs = 0.0.0.0/0
AllowedIPs = 10.10.10.0/24
So traffic will be routed through VPN only when the destination address is in the 10.10.10.0/24 IP range. Save and close the file. Then restart WireGuard client.
sudo systemctl restart [email protected]
VPN Kill Switch
By default, your computer can access the Internet via the normal gateway when the VPN connection is disrupted. You may want to enable the kill switch feature, which prevents the flow of unencrypted packets through non-WireGuard interfaces.
Stop the WireGuard client process.
sudo systemctl stop [email protected]
Edit the client configuration file.
sudo nano /etc/wireguard/wg-client0.conf
PostUp = iptables -I OUTPUT ! -o %i -m mark ! --mark $(wg show %i fwmark) -m addrtype ! --dst-type LOCAL -j REJECT PreDown = iptables -D OUTPUT ! -o %i -m mark ! --mark $(wg show %i fwmark) -m addrtype ! --dst-type LOCAL -j REJECT
[Interface] Address = 10.10.10.2/24 DNS = 10.10.10.1 PrivateKey = PostUp = iptables -I OUTPUT ! -o %i -m mark ! --mark $(wg show %i fwmark) -m addrtype ! --dst-type LOCAL -j REJECT PreDown = iptables -D OUTPUT ! -o %i -m mark ! --mark $(wg show %i fwmark) -m addrtype ! --dst-type LOCAL -j REJECT [Peer] PublicKey = AllowedIPs = 0.0.0.0/0 Endpoint = :51820 PersistentKeepalive = 25
Save and close the file. Then start the WireGuard client.
sudo systemctl start [email protected]
Wrapping Up
That’s it! I hope this tutorial helped you install and configure OpenConnect VPN on CentOS 8/RHEL 8 server. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks. Take care 🙂
Creating VPN Accounts
Now use the ocpasswd tool to generate VPN accounts.
sudo ocpasswd -c /etc/ocserv/ocpasswd
Now we can start the ocserv
serice.
sudo systemctl start ocserv
And enable auto-start at boot time.
sudo systemctl enable ocserv
You can check its status with:
systemctl status ocserv
ocserv.service - OpenConnect SSL VPN server Loaded: loaded (/usr/lib/systemd/system/ocserv.service; ; vendor preset: disabled) Active: since Fri 2020-01-03 19:04:53 CST; 15s ago Docs: man:ocserv(8) Main PID: 19851 (ocserv-main) Tasks: 2 (limit: 5061) Memory: 3.2M CGroup: /system.slice/ocserv.service ├─19851 ocserv-main └─19853 ocserv-sm
Hint: If the above command doesn’t quit immediately, you can press the Q key to gain back control of the terminal.
By default OpenConnect VPN server listens on TCP and UDP port 443. If it’s being used by a web server, then the VPN server can’t be started. We will see how to make OpenConnect VPN server and web server use the same port later.
Wrapping Up
That’s it! I hope this tutorial helped you install and configure WireGuard on CentOS/RHEL. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks 🙂
Virtual Hosting
To add a new virtual host in ocserv, first you need to use the method in step 4 to obtain a TLS certificate for the new virtual host. Then edit ocserv configuration file.
sudo nano /etc/ocserv/ocserv.conf
[vhost:] #Allow password authentication and certificate authentication enable-auth = "plain[passwd=/etc/ocserv/ocpasswd]" auth = "certificate" tcp-port = 443 #uncomment the two lines if ocserv runs behind HAProxy. #listen-host = 127.0.0.1 #listen-proxy-proto = true # SSL/TLS configuration ca-cert = /etc/ocserv/ssl/ca-cert.pem server-cert = /etc/letsencrypt/live//fullchain.pem server-key = /etc/letsencrypt/live//privkey.pem cert-user-oid = 0.9.2342.19200300.100.1.1 #Networking configuration. Use a different network range for this virtual host. device = vpns ipv4-network = 10.10.20.0 ipv4-netmask = 255.255.255.0 route = default dns = 8.8.8.8 tunnel-all-dns = true compression = true max-clients = 0 max-same-clients = 0 try-mtu-discovery = true idle-timeout=1200 mobile-idle-timeout=2400 config-per-user = /etc/ocserv/config-per-user/ config-per-group = /etc/ocserv/config-per-group/
Save and close the file. Then restart ocserv.
sudo systemctl restart ocserv
VPN service unavailable; reason: Server configuration error
no networks are configured; rejecting client
Generate Public/Private Keypair
Server
Create a directory for WireGuard.
sudo mkdir -p /etc/wireguard/
wg genkey | sudo tee /etc/wireguard/server_private.key | wg pubkey | sudo tee /etc/wireguard/server_public.key
Client
Create a directory for WireGuard.
sudo mkdir -p /etc/wireguard/
wg genkey | sudo tee /etc/wireguard/client_private.key | wg pubkey | sudo tee /etc/wireguard/client_public.key
Open WireGuard Port in Firewall
sudo firewall-cmd --permanent --add-port=51820/udp sudo systemctl reload firewalld
Features of OpenConnect VPN server
- Lightweight and fast. In my test, I can watch YouTube 4K videos with OpenConnect VPN. YouTube is blocked in my country (China).
- Runs on Linux and most BSD servers.
- Compatible with Cisco AnyConnect client
- There is OpenConnect client software for Linux, macOS, Windows, and OpenWRT. For Android and iOS, you can use the Cisco AnyConnect Client.
- Supports password authentication and certificate authentication
- Supports RADIUS accounting.
- Supports virtual hosting (multiple domains)
- Easy to set up
sudo openconnect -b
The openconnect
client software is available for Debian, Ubuntu, Fedora, RHEL, CentOS, Arch Linux, and OpenSUSE. You can easily install it with your package manager.
sudo apt install openconnect sudo dnf install openconnect sudo pacman -S openconnect
Requirements
- 30 days free trial.
- Starts at $4/month (1GB RAM)
- High-performance KVM-based VPS
- 9 data centers around the world, including United States, Canada, UK, Germany, The Netherlands, Hong Kong, and Isreal.
You also need a domain name to enable HTTPS for OpenConnect VPN. I registered my domain name from NameCheap because the price is low and they give whois privacy protection free for life.
Enable IP Forwarding on the Server
In order for the VPN server to route packets between VPN clients and the Internet, we need to enable IP forwarding. Edit sysctl.conf
file.
sudo nano /etc/sysctl.conf
net.ipv4.ip_forward = 1
Save and close the file. Then apply the changes with the below command. The -p option will load sysctl settings from /etc/sysctl.conf file. This command will preserve our changes across system reboots.
sudo sysctl -p
Install OpenConnect VPN Server (ocserv) on CentOS 8
sudo dnf install epel-release sudo dnf install ocserv
Enable IP Forwarding in Linux Kernel
echo "net.ipv4.ip_forward = 1" | sudo tee /etc/sysctl.d/60-custom.conf
echo "net.core.default_qdisc=fq" | sudo tee -a /etc/sysctl.d/60-custom.conf echo "net.ipv4.tcp_congestion_control=bbr" | sudo tee -a /etc/sysctl.d/60-custom.conf
Then apply the changes with the below command. The -p option will load sysctl settings from /etc/sysctl.d/60-custom.conf file. This command will preserve our changes across system reboots.
sudo sysctl -p /etc/sysctl.d/60-custom.conf
Install Let’s Encrypt Client (Certbot) on CentOS 8 Server
The gnutls-utils
package installed along with ocserv
provides tools to create your own CA and server certificate, but we will obtain and install Let’s Encrypt certificate. The advantage of using Let’s Encrypt certificate is that it’s free, easier to set up, and trusted by VPN client software.
sudo dnf install certbot
To check the version number, run
certbot --version
certbot 1.14.0
Open Ports in Firewall
sudo firewall-cmd --permanent --add-port=443/tcp sudo firewall-cmd --permanent --add-port=443/udp
We also need to open TCP port 80 to obtain TLS certificate from Let’s Encrypt.
sudo firewall-cmd --permanent --add-port=80/tcp
Reload firewall for the changes to take effect.
sudo systemctl reload firewalld
Configure IP Masquerading on the Server
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.10.10.0/24" masquerade' sudo systemctl reload firewalld
This will hide your VPN network from the outside world. So the Internet can only see your VPN server’s IP, but can’t see your VPN client’s IP, just like your home router hides your private home network.
If your CentOS/RHEL can’t find the firewall-cmd
command, you need to install firewalld
and start the service.
sudo dnf install firewalld sudo firewall-cmd --permanent --add-port=22/tcp sudo systemctl start firewalld
Install and Use OpenConnect VPN client on CentOS 8/Fedora Desktop
sudo dnf install openconnect
On CentOS 8, you need to enable the EPEL repository in order to install the client.
sudo dnf install epel-release sudo dnf install openconnect
Then you can connect to VPN server from the command line like below. -b
flag will make it run in the background after the connection is established.
sudo openconnect -b
By default, openconnect client sends request to port 443 of the server. If you configured a different port for the server, then you can add the port number.
sudo openconnect -b vpn.example.com:
Got CONNECT response: HTTP/1.1 200 CONNECTED CSTP connected. DPD 90, Keepalive 32400 Connected as 10.10.10.139, using SSL + lz4 Continuing in background; pid 2137 Established DTLS connection (using GnuTLS). Ciphersuite (DTLS1.2)-(PSK)-(AES-256-GCM).
If the connection failed, you can check the ocserv log to find out why. (Perhaps you didn’t enter the password correctly.)
sudo journaltcl -eu ocserv
To stop the connection, run:
sudo pkill openconnect
echo -n | sudo openconnect -b -u --passwd-on-stdin
If you are successfully connected to the VPN server, but your public IP address doesn’t change, that’s because IP forwarding or IP masquerading is not working.
Obtain a Trusted TLS Certificate from Let’s Encrypt
I recommend using the standalone
or webroot
plugin to obtain TLS certificate.
Standalone Plugin
sudo certbot certonly --standalone --preferred-challenges http --agree-tos --email -d
certonly
: Obtain a certificate but don’t install it.--standalone
: Use the standalone plugin to obtain a certificate--preferred-challenges http
: Perform http-01 challenge to validate our domain, which will use port 80.--agree-tos
: Agree to Let’s Encrypt terms of service.--email
: Email address is used for account registration and recovery.-d
: Specify your domain name.
Using webroot Plugin
If your CentOS 8 server has a web server listening on port 80 and 443, then it’s a good idea to use the webroot plugin to obtain a certificate because the webroot plugin works with pretty much every web server and we don’t need to install the certificate in the web server.
First, you need to create a virtual host for vpn.example.com
.
Apache
If you are using Apache web server, then create virtual host under /etc/httpd/conf.d/
directory.
sudo nano /etc/httpd/conf.d/.conf
<VirtualHost *:80> ServerName DocumentRoot /var/www/html/ </VirtualHost>
Save and close the file. Reload Apache for the changes to take effect.
sudo systemctl reload httpd
sudo certbot certonly --webroot --agree-tos --email -d -w /var/www/html/
Nginx
If you are using Nginx web server, then create virtual host under /etc/nginx/conf.d/
.
sudo nano /etc/nginx/conf.d/.conf
server { listen 80; server_name ; root /usr/share/nginx/html/; location ~ /.well-known/acme-challenge { allow all; } }
Save and close the file. Reload Nginx for the changes to take effect.
sudo systemctl reload nginx
sudo certbot certonly --webroot --agree-tos --email -d -w /usr/share/nginx/html/
Per-User or Per Group Configuration
config-per-user = /etc/ocserv/config-per-user/ config-per-group = /etc/ocserv/config-per-group/
sudo mkdir /etc/ocserv/config-per-user/ sudo mkdir /etc/ocserv/config-per-group/
sudo nano /etc/ocserv/config-per-user/user1
You can also create the group1
file to allow custom configuration for the group named group1
.
sudo nano /etc/ocserv/config-per-group/group1
You can add something like below in the file.
route = 10.10.10.0/255.255.255.0
- You just want the VPN clients to be able to browse internal resources and don’t want all the traffic to go through the VPN server.
- You need to build a private network for cloud servers.
- The client needs to connect to multiple VPNs. One VPN could use split tunneling and the other use a full tunnel.
Save and close the file. Restart ocserv
for the changes to take effect.
Edit OpenConnect VPN Server Configuration File
Edit ocserv configuration file.
sudo nano /etc/ocserv/ocserv.conf
auth = "pam"
auth = "plain[passwd=/etc/ocserv/ocpasswd]"
Note: Ocserv supports client certificate authentication, but Let’s Encrypt does not issue client certificate. If you want to enable certificate authentication, you need to set up your own CA to issue client certificate.
tcp-port = 443 udp-port = 443
Comment out the UDP port. (We will use TCP BBR algorithm to boost TCP speed.)
tcp-port = 443 #udp-port = 443
If you don’t want ocserv to use TCP port 443 (there’s a web server using port 443?), then change the TCP port number. Otherwise leave it alone.
server-cert = /etc/pki/ocserv/public/server.crt server-key = /etc/pki/ocserv/private/server.key
Replace the default setting with the path of Let’s Encrypt server certificate and server key file.
server-cert = /etc/letsencrypt/live//fullchain.pem server-key = /etc/letsencrypt/live//privkey.pem
compression = true
Then, set the maximal number of clients. Default is 16. Set to zero for unlimited.
max-clients = 0
max-same-clients = 0
By default, keepalive packets are sent every 32400 seconds (9 hours). I prefer to use a short time (30 seconds) to reduce the chance of VPN connection dropout.
keepalive = 30
try-mtu-discovery = true
idle-timeout=1200 mobile-idle-timeout=2400
After that, set the default domain to vpn.example.com
.
default-domain =
#ipv4-network = 192.168.1.0 #ipv4-netmask = 255.255.255.0
We can use another private IP address range (such as 10.10.10.0/24) to avoid IP address collision, so uncomment the above two lines and change the value of ipv4-network
to 10.10.10.0
.
ipv4-network = 10.10.10.0 ipv4-netmask = 255.255.255.0
ipv6-network = fda9:4efe:7e3b:03ea::/48 ipv6-subnet-prefix = 64
ipv6-network = fda9:4efe:7e3b:03ea::/64
Please change it to:
ipv6-network = fda9:4efe:7e3b:03ea::/48
tunnel-all-dns = true
Change DNS resolver address. You can use Google’s public DNS server.
dns = 8.8.8.8 dns = 8.8.4.4
dns = 1.1.1.1 dns = 1.0.0.1
Note: If you are a VPN service provider, it’s a good practice to run your own DNS resolver. If there’s a DNS resolver running on the same server, then specify the DNS as
dns = 10.10.10.1
10.10.10.1 is the IP address of OpenConnect VPN server in the VPN LAN. This will speed up DNS lookups a little bit for clients because the network latency between the VPN server and the DNS resolver is eliminated.
#route = 10.10.10.0/255.255.255.0 #route = 192.168.0.0/255.255.0.0 #route = fef4:db8:1000:1001::/64 #no-route = 192.168.5.0/255.255.255.0
#user-profile = profile.xml
Failed to download the AnyConnect profile. Please try again.
Save and close the file.
Speed Optimization
OpenConnect by default uses TLS over UDP protocol (DTLS) to achieve faster speed, but UDP can’t provide reliable transmission. TCP is slower than UDP but can provide reliable transmission. One optimization tip I can give you is to disable DTLS, use standard TLS (over TCP), then enable TCP BBR to boost TCP speed.
You may also want to disable DTLS to bypass firewall restrictions because DTLS uses UDP port 443. Standard TLS uses TCP port 443.
udp-port = 443
Save and close the file. Then restart ocserv service.
sudo systemctl restart ocserv.service
In my test, standard TLS with TCP BBR enabled is two times faster than DTLS.
Another very important factor affecting speed is how good the connection between your local computer and the VPN server is. If you live in the middle east and the VPN server is located in the U.S, the speed would be slow. Choose a data center that’s close to where you live.
Troubleshooting Tips
ping: sendmsg: Required key not available
it might be that the AllowedIPs
parameter is wrong, like a typo.
If the VPN tunnel is successfully established, but the client public IP address doesn’t change, that’s because the masquerading in the firewall is not working. I once had a typo in the firewall rules, which caused my computer not being able to browse the Internet.
If your VPN still doesn’t work, try restarting the VPN server.
sudo systemctl restart [email protected]
Then stop the VPN client.
sudo systemctl stop [email protected]
And upgrade software packages on the VPN client.
sudo dnf update
Next, reboot the VPN client.
sudo shutdown -r now
sudo systemctl start [email protected]
Install a DNS Resolver on the Server
Since we specify the VPN server as the DNS server for client, we need to run a DNS resolver on the VPN server. We can install the bind9 DNS server.
sudo dnf install bind
Start BIND 9 with:
sudo systemctl start named
And enable auto start at boot time:
sudo systemctl enable named
You can check its status with:
systemctl status named
named.service - Berkeley Internet Name Domain (DNS) Loaded: loaded (/usr/lib/systemd/system/named.service; enabled; vendor preset: disable> Active: since Sun 2020-05-17 11:07:34 EDT; 9s ago Process: 7203 ExecStop=/bin/sh -c /usr/sbin/rndc stop > /dev/null 2>&1 || /bin/kill -TE> Process: 7218 ExecStart=/usr/sbin/named -u named -c ${NAMEDCONF} $OPTIONS (code=exited,> Process: 7215 ExecStartPre=/bin/bash -c if [ ! "$DISABLE_ZONE_CHECKING" == "yes" ]; the> Main PID: 7220 (named) Tasks: 4 (limit: 5045) Memory: 55.5M CGroup: /system.slice/named.service └─7220 /usr/sbin/named -u named -c /etc/named.conf -4
Hint: If the above command doesn’t quit immediately, press Q.
Edit the BIND main configuration file /etc/named.conf
.
sudo nano /etc/named.conf
listen-on port 53 { 127.0.0.1; }; listen-on-v6 port 53 { ::1; };
This makes named
listen on localhost only. If you want to allow clients in the same network to query domain names, then comment out these two lines. (add double slashes at the beginning of each line)
// listen-on port 53 { 127.0.0.1; }; // listen-on-v6 port 53 { ::1; };
allow-query { localhost; };
Add the 10.10.10.0/24 network range so that VPN clients can send DNS queries. Note that you need to end each network range with a semicolon.
allow-query { localhost; 10.10.10.0/24; };
Save and close the file. Restart BIND9 for the changes to take effect.
sudo systemctl restart named
sudo firewall-cmd --zone=public --permanent --add-rich-rule='rule family="ipv4" source address="10.10.10.0/24" accept'
Troubleshooting Tips
Note that if you are using OpenVZ VPS, make sure you enable the TUN virtual networking device in VPS control panel. (If you use Vultr VPS, then you have KVM-based VPS, so you don’t have to worry about this.)
If you encounter any problem, then check OpenConnect VPN server log.
sudo journalctl -eu ocserv.service
If ocserv tells you that it can’t load the /etc/ocserv/ocserv.conf
file, you can stop ocserv.
sudo systemctl stop ocserv
Then run it in the foreground with debugging enabled.
sudo /usr/sbin/ocserv --foreground --pid-file /run/ocserv.pid --config /etc/ocserv/ocserv.conf --debug=10
Then output might give you some clues why ocserv isn’t working.
If you are successfully connected to the VPN server, but you can’t browse the Internet, that’s because IP forwarding or IP masquerading is not working.
No Tap-Windows Adapter installed on this system
If you use the OpenConnect GUI Windows client and found the “No Tap-Windows Adapter installed on this system” error in the logs (View – Log Window), this is likely because you have install other VPN clients afterward like OpenVPN.
To fix this error, you need to uninstall OpenConnect GUI client and reinstall it. In the setup wizard, you will have the option to install the TAP driver.
Why Set Up Your Own VPN Server?
- Maybe you are a VPN service provider or a system administrator, which behooves you to set up your own VPN server.
- You don’t trust the no logging policy of VPN service providers, so you go the self-host route.
- You can use VPN to implement network security policy. For example, if you run your own email server, you can require users to log in only from the IP address of the VPN server by creating an IP address whitelist in the firewall. Thus, your email server is hardened to prevent hacking activities.
- Perhaps you are just curious to know how VPN server works.
Auto-Renew Let’s Encrypt Certificate
sudo crontab -e
@daily certbot renew --quiet && systemctl restart ocserv
How to Set Up VPN Relay
Suppose there are two servers: server A and server B.
- You have a good connection to server A. Latency is very low and no packet is dropped.
- You have a bad connection to server B. Latency is high and there’s packet being dropped.
- The connection between server A and server B is good.
Naturally, you want to install VPN on server A. But what if you want the Internet to see your traffic coming from server B’s IP address? Well, you can install ocserv VPN on server B, then set up HAProxy on server A to proxy the traffic between your computer and server B.
On server A, install HAProxy.
sudo dnf install haproxy
Edit main configuration file.
sudo nano /etc/haproxy/haproxy.cfg
Create a front end and back end just like before. Replace 12.34.56.78 with server A’s public IP address. Replace 12.34.56.79 with server B’s public IP address.
frontend https bind :443 mode tcp tcp-request inspect-delay 5s tcp-request content accept if { req_ssl_hello_type 1 } use_backend ocserv if { req_ssl_sni -i } default_backend ocserv backend ocserv mode tcp option ssl-hello-chk server ocserv :443 send-proxy-v2
Save and close the file. On server B, you should configure ocserv to listen on the public IP address and enable proxy protocol just like before. After that, edit the A record of vpn.example.com. It should be pointed to the IP address of server A.
Restart HAProxy and Ocserv and it should be working.
Note: If server B also uses HAProxy, then you should remove the send-proxy-v2
parameter in the above HAProxy configuration.
Requirements
- 30 days free trial.
- Starts at $4/month (1GB RAM)
- High-performance KVM-based VPS
- 9 data centers around the world, including United States, Canada, UK, Germany, The Netherlands, Hong Kong, and Isreal.
This tutorial assumes that the VPN server and VPN client are both running CentOS/RHEL operating system.
How to Disable TLS 1. 0 and TLS 1. 1 in ocserv
The PCI council deprecated TLS 1.0 in June 30, 2018 and mainstream web browsers are going to disable TLS 1.0 and TLS 1.1 in 2020. We should do the same with VPN server. Edit the main configuration file.
sudo nano /etc/ocserv/ocserv.conf
tls-priorities = "NORMAL:%SERVER_PRECEDENCE:%COMPAT:-VERS-SSL3.0"
To disable TLS 1.0 and TLS 1.1 in OpenConnect VPN server, replace it with:
tls-priorities = "NORMAL:%SERVER_PRECEDENCE:%COMPAT:-RSA:-VERS-SSL3.0:-ARCFOUR-128:-VERS-TLS1.0:-VERS-TLS1.1"
Save and close the file. Then restart ocserv.
sudo systemctl restart ocserv
Now ocserv will only accept TLS 1.3 and TLS 1.2. For further information on configuring the TLS parameter in ocserv, please see GnuTLS priority strings.
openssl s_client -connect :443 -tls1
And check TLS 1.1
openssl s_client -connect :443 -tls1_1
New, (NONE), Cipher is (NONE) Secure Renegotiation IS NOT supported
Create WireGuard Configuration File
Server
Use a command-line text editor like Nano to create a WireGuard configuration file on the CentOS/RHEL server. wg0
will be the network interface name.
sudo dnf install nano sudo nano /etc/wireguard/wg0.conf
[Interface] Address = 10.10.10.1/24 ListenPort = 51820 PrivateKey = [Peer] PublicKey = AllowedIPs = 10.10.10.2/32
- Address: Specify the private IP address of the VPN server. Here I’m using the 10.10.10.0/24 network range, so it won’t conflict with your home network range. (Most home routers use 192.168.0.0/24 or 192.168.1.0/24). 10.10.10.1 is the private IP address for the VPN server.
- PrivateKey: The private key of VPN server, which can be found in the
/etc/wireguard/server_private.key
file on the server. - ListenPort: WireGuard VPN server will be listening on UDP port 51820, which is the default.
- PublicKey: The public key of VPN client, which can be found in the
/etc/wireguard/client_public.key
file on the client computer. - AllowedIPs: IP addresses the VPN client is allowed to use. In this example, the client can only use the 10.10.10.2 IP address inside the VPN tunnel.
Save and close the file. (To save a file in Nano text editor, press Ctrl+O
, then press Enter to confirm. Press Ctrl+X
to exit.)
sudo chmod 600 /etc/wireguard/ -R
Client
Use a command-line text editor like Nano to create a WireGuard configuration file on your local CentOS/RHEL computer. wg-client0
will be the network interface name.
sudo nano /etc/wireguard/wg-client0.conf
[Interface] Address = 10.10.10.2/24 DNS = 10.10.10.1 PrivateKey = [Peer] PublicKey = AllowedIPs = 0.0.0.0/0 Endpoint = :51820 PersistentKeepalive = 25
- Address: Specify the private IP address of the VPN client.
- DNS: specify 10.10.10.1 (the VPN server) as the DNS server. It will be configured via the
resolvconf
command. You can also specify multiple DNS servers for redundancy like this:DNS = 10.10.10.1 8.8.8.8
- PrivateKey: The client’s private key, which can be found in the
/etc/wireguard/client_private.key
file on the client computer. - PublicKey: The server’s public key, which can be found in the
/etc/wireguard/server_public.key
file on the server. - AllowedIPs: 0.0.0.0/0 represents the whole Internet, which means all traffic to the Internet should be routed via the VPN.
- Endpoint: The public IP address and port number of VPN server. Replace 12.34.56.78 with your server’s real public IP address.
- PersistentKeepalive: Send an authenticated empty packet to the peer every 25 seconds to keep the connection alive. If PersistentKeepalive isn’t enabled, the VPN server might not be able to ping the VPN client.
Save and close the file.
sudo chmod 600 /etc/wireguard/ -R
Configure VPN Client on iOS/Andorid
Since I have an iPhone, I will show you how to configure WireGuard client on iOS. Install the WireGuard app from the App store. Then open this app and click the Add a tunnel button.
You have 3 methods to create a new WireGuard tunnel.
- create from file or archive
- create from QR code
- Create from scratch
wg genkey | sudo tee /etc/wireguard/ios_private.key | wg pubkey | sudo tee /etc/wireguard/ios_public.key
Next, create a WireGuard config file for the iOS client.
sudo nano /etc/wireguard/ios.conf
[Interface] Address = /24 DNS = 10.10.10.1 PrivateKey = [Peer] PublicKey = AllowedIPs = 0.0.0.0/0 Endpoint = :51820 PersistentKeepalive = 25
- Address: Specify the private IP address for the iOS client.
- DNS: specify 10.10.10.1 (the VPN server) as the DNS server. You can also specify multiple DNS servers for redundancy like this:
DNS = 10.10.10.1,8.8.8.8
. Note that the iOS app doesn’t support theDNS = 10.10.10.1 8.8.8.8
syntax. - PrivateKey: The iOS client’s private key, which can be found in the
/etc/wireguard/ios_private.key
file. - PublicKey: The server’s public key, which can be found in the
/etc/wireguard/server_public.key
file on the server. - AllowedIPs: 0.0.0.0/0 represents the whole Internet, which means all traffic to the Internet should be routed via the VPN.
- Endpoint: The public IP address and port number of VPN server. Replace 12.34.56.78 with your server’s real public IP address.
- PersistentKeepalive: Send an authenticated empty packet to the peer every 25 seconds to keep the connection alive. If PersistentKeepalive isn’t enabled, the VPN server might not be able to ping the VPN client.
sudo cat /etc/wireguard/ios.conf | qrencode -t ansiutf8
Next, scan a QR code from the iOS WireGuard app, so the content in the /etc/wireguard/ios.conf
file will be imported to the WireGuard iOS client.
sudo nano /etc/wireguard/wg0.conf
[Interface] Address = 10.10.10.1/24 PrivateKey = UIFH+XXjJ0g0uAZJ6vPqsbb/o68SYVQdmYJpy/FlGFA= ListenPort = 51820 [Peer] PublicKey = 75VNV7HqFh+3QIT5OHZkcjWfbjx8tc6Ck62gZJT/KRA= AllowedIPs = 10.10.10.2/32 [Peer] # iOS client PublicKey = YYh4/1Z/3rtl0i7cJorcinB7T4UOIzScifPNEIESFD8= AllowedIPs = 10.10.10.3/32
Save and close the file. Then restart the WireGuard VPN server.
sudo systemctl restart [email protected]
Now you can establish WireGuard VPN connection from the iOS app.
OpenConnect GUI Client for Windows and MacOS
They can be downloaded from OpenConnect GUI Github Page.
Features of WireGuard VPN
- Lightweight and super fast speed, blowing OpenVPN out of the water.
- Cross-platform. WireGuard can run on Linux, BSD, macOS, Windows, Android, iOS, and OpenWRT.
- User authentication is done by exchanging public keys, similar to SSH keys.
- It assigns static tunnel IP addresses to VPN clients. Some folks may not like it, but it can be useful in some cases.
- Mobile devices can switch between Wi-Fi and mobile network seamlessly without dropping any connectivity.
- It aims to replace OpenVPN and IPSec in most use cases.
Speed
OpenConnect VPN is pretty fast. I can use it to watch 4k videos on YouTube. As you can see, the connection speed is 63356 Kbps, which translates to 61 Mbit/s.
And here’s the test results on speedtest.net.
Configure Windows Client
Download the WireGuard installer for Windows.
Once it’s installed, start the WireGuard program. You need to right-click on the left sidebar to create a new empty tunnel. It will automatically create a public/private key for the Windows client.
Now you need to add other information.
[Interface] PrivateKey = Address = /24 DNS = 10.10.10.1 [Peer] # VPN server PublicKey = AllowedIPs = 0.0.0.0/0 Endpoint = :51820 PersistentKeepalive = 25
- Address: Specify the private IP address for the Windows client.
- DNS: specify 10.10.10.1 (the VPN server) as the DNS server. You can also specify multiple DNS servers for redundancy like this:
DNS = 10.10.10.1,8.8.8.8
. Note that the Windows app doesn’t support theDNS = 10.10.10.1 8.8.8.8
syntax. - PrivateKey: The Windows client’s private key, which is automatically created.
- PublicKey: The server’s public key, which can be found in the
/etc/wireguard/server_public.key
file on the server. - AllowedIPs: 0.0.0.0/0 represents the whole Internet, which means all traffic to the Internet should be routed via the VPN.
- Endpoint: The public IP address and port number of VPN server. Replace 12.34.56.78 with your server’s real public IP address.
- PersistentKeepalive: Send an authenticated empty packet to the peer every 25 seconds to keep the connection alive. If PersistentKeepalive isn’t enabled, the VPN server might not be able to ping the VPN client.
Hint: On Windows, you can use the PowerShell program to SSH into your Linux server.
Save the configuration.
sudo nano /etc/wireguard/wg0.conf
[Interface] Address = 10.10.10.1/24 PrivateKey = UIFH+XXjJ0g0uAZJ6vPqsbb/o68SYVQdmYJpy/FlGFA= ListenPort = 51820 [Peer] PublicKey = 75VNV7HqFh+3QIT5OHZkcjWfbjx8tc6Ck62gZJT/KRA= AllowedIPs = 10.10.10.2/32 [Peer] # iOS client PublicKey = YYh4/1Z/3rtl0i7cJorcinB7T4UOIzScifPNEIESFD8= AllowedIPs = 10.10.10.3/32 [Peer] # Windows client PublicKey = wJpwC/gCWXZTGa5lQReKowRvymaaEUav0N1qeK74HlQ= AllowedIPs = 10.10.10.4/32
Save and close the file. Then restart the WireGuard VPN server.
sudo systemctl restart [email protected]
Now you can establish WireGuard VPN connection on Windows.
Install WireGuard on CentOS/RHEL Server and Desktop
CentOS 8/Rocky Linux 8/Alma Linux 8
sudo dnf install elrepo-release epel-release -y sudo dnf install kmod-wireguard wireguard-tools -y
RHEL 8
sudo dnf install https://www.elrepo.org/elrepo-release-8.el8.elrepo.noarch.rpm sudo dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm sudo dnf install kmod-wireguard wireguard-tools -y
CentOS/RHEL 7
sudo yum install epel-release https://www.elrepo.org/elrepo-release-7.el7.elrepo.noarch.rpm sudo yum install yum-plugin-elrepo sudo yum install kmod-wireguard wireguard-tools -y
Then use the same commands to install WireGuard on your local CentOS/RHEL computer (the VPN client).
How to Run Multiple Instances of ocserv
One ocserv process can bind to only one TCP or UDP port on your server. If you want to allow ocserv to bind to multiple TCP or UDP ports, then you need to run multiple ocserv processes. It’s very simple. Copy the /usr/lib/systemd/system/ocserv.service
to a new file.
sudo cp /usr/lib/systemd/system/ocserv.service /etc/systemd/system/ocserv2.service
Then edit the new file.
sudo nano /etc/systemd/system/ocserv2.service
/etc/ocserv/ocserv.conf
/etc/ocserv/ocserv2.conf
Save and close the file. Next, you can edit the /etc/ocserv/ocserv2.conf
file and add your custom configurations. Once you are done, start the second ocserv service.
sudo systemctl start ocserv2
If You Appreciate What We Do Here On TecMint, You Should Consider
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
If You Appreciate What We Do Here On TecMint, You Should Consider
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
If You Appreciate What We Do Here On TecMint, You Should Consider
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.