- Connecting to Access Server with Linux
- Client software choice
- Linux Packages Discussed
- OpenVPN 3 Linux Client
- OpenVPN open source OpenVPN CLI program
- Ubuntu network management program
- Простая настройка OpenVPN Linux
- Настройка OpenVPN сервера в Linux
- Настройка клиента OpenVPN
- Выводы
- Installing openvpn on linux
Connecting to Access Server with Linux
Client software choice
Connecting to OpenVPN Access Server from Linux requires a client program. It will capture the traffic you wish to send through the OpenVPN tunnel, encrypting it and passing it to the OpenVPN server. And of course, the reverse, to decrypt the return traffic.
Linux Packages Discussed
OpenVPN Access Server | openvpn-as |
OpenVPN 3 Linux Client | openvpn3 |
OpenVPN open source | openvpn |
OpenVPN 3 Linux Client
The OpenVPN 3 Linux project is a new client built on top of the OpenVPN 3 Core Library. This client is the official OpenVPN Linux Client program. You can find an overview of the features, frequently asked questions, and instructions on installing the openvpn3 package on our OpenVPN 3 for Linux site.
After following the instructions there to install the client, you’ll need a connection profile. This is a file generated by your OpenVPN Access Server installation for your specific user account. It contains the required certificates and connection settings. Go to the Client web interface of your Access Server (the main address, not the /admin portion). Log in with your user credentials. You will be shown a list of files available to download. Pick the user-locked profile or the auto-login profile, and you will be sent a client.ovpn file. Save this file to your Linux operating system.
Once you’ve moved the file to your Linux system, you can import it.
You can start a new VPN session:
You can manage a running VPN session:
And so on. More details can be found here: OpenVPN3Linux.
OpenVPN open source OpenVPN CLI program
The open source project client program can also connect to the Access Server. The package is available in most distributions and is known simply as openvpn. It supports the option to connect to multiple OpenVPN servers simultaneously, and it comes with a service component that can automatically and silently start any auto-login profiles it finds in the /etc/openvpn folder, even before a user has logged in. This service component can be set to automatically start at boot time with the tools available in your Linux distribution if supported. On Ubuntu and Debian, when you install the openvpn package, it is automatically configured to start at boot time.
To install the OpenVPN client on Linux, it is possible in many cases to just use the version that is in the software repository for the Linux distribution itself. If you run into any connectivity problems when using outdated software, it may be due to a possible lack of support for higher TLS versions in older versions of OpenVPN. Follow the instructions found on the open source openvpn community wiki if you wish to install the OpenVPN client on your Linux system.
After installing, you will need a connection profile. This is a file generated by your OpenVPN Access Server installation for your specific user account. It contains the required certificates and connection settings. Go to the Client web interface of your Access Server (the main address, not the /admin portion). Log in with your user credentials. You will be shown a list of files available to you for download. Pick the user-locked profile or the auto-login profile, and you will be sent a client.ovpn file. Save this file to your Linux operating system somewhere. OpenVPN Access Server supports server-locked, user-locked, and auto-login profiles, but the OpenVPN command line client is only able to connect with user-locked or auto-login connection profiles.
We are assuming you are going to start the connection through either the command line as a root user, or via the service daemon. If you want unprivileged users to be able to make a connection, take a look at the community wiki for more information on how to implement that. Here we are going to focus on the simplest implementation; run the connection as root user directly, or via the service daemon.
Start a connection with an auto-login profile manually:
Start a connection with a user-locked profile manually:
If you use Google Authenticator or another extra factor authentication, add the auth-retry parameter:
To start an auto-login connection via the service daemon, place client.ovpn in /etc/openvpn/ and rename the file. It must end with .conf as file extension. Ensure the service daemon is enabled to run after a reboot, and then simply reboot the system. The auto-login type profile will be picked up automatically and the connection will start itself. You can verify this by checking the output of the ifconfig command; you should see a tun0 network adapter in the list.
One major feature that is missing with the command line client is the ability to automatically implement DNS servers that are pushed by the VPN server. It is possible, but it requires you to install a DNS management program such as resolvconf or openresolv, and it may or may not clash with existing network management software in your OS. The idea here, however, is that you use a script that runs when the connection goes up, and when it goes down, that uses resolvconf or openresolv to implement the DNS servers for you. The reason why this client is not able to manage it completely by itself is mainly because in an operating system like Windows, Macintosh, Android, or iOS, there is already an established single method of handling DNS management. It is therefore easy for us to create a software client for those operating systems that already knows how to handle DNS. But Linux is available in so many variations and also supports different programs and methods of implementing DNS servers, and so it was only reasonable to leave built-in DNS support out of the OpenVPN program and instead to provide, where possible, a script that handles DNS implementation. Such a script could even be written by yourself to do whatever tasks are necessary to implement the DNS servers in your unique situation.
Fortunately on Ubuntu and Debian, for example, there is the /etc/openvpn/update-resolv-conf script that comes with the openvpn package that handles DNS implementation for these operating systems. You need only to activate the use of these by following the instructions:
Open your client.ovpn file in a text editor:
At the very bottom simply add these lines:
The first line enables the use of external scripts to handle the DNS implementation tasks. The up and down lines are there to implement DNS servers pushed by the VPN server when the connection goes up, and afterwards to undo it, when the connection goes down.
Ubuntu network management program
There is also the option of connecting through the GUI using the openvpn extension for the Gnome network manager plugin. But this is currently a bit tricky to set up. There is for example the incorrect assumption that all VPNs will be able to redirect Internet traffic, and older versions might not understand the .ovpn file format, requiring you to split up the certificate embedded in it into separate file. And you would likely have to dig into the options to ensure that a default Internet traffic route going through the VPN server is not always enabled by default, especially for servers where you only give access to some internal resources, and not the entire Internet. However the advantage of using the GUI component is that you can start/stop the connection from the desktop environment on Linux.
Источник
Простая настройка OpenVPN Linux
OpenVPN часто используется для создания виртуальных безопасных сетей между компьютерами, которые находятся на очень большом расстоянии, но при этом между ними нужно получить шифрованное безопасное соединение, которое невозможно перехватить и прослушать.
Другое применение для OpenVPN — это обход блокировок различных интернет ресурсов. Существуют различные серверы OpenVPN серверы в интернете, но будет намного надежнее если развернуть OpenVPN на своем сервере. Мы рассматривали процесс в статье установка OpenVPN на Ubuntu, но для новичков это достаточно сложно. В этой инструкции мы рассмотрим как выполняется настройка OpenVPN linux с помощью скрипта openvpn-install, который упрощает процесс установки и настройки в несколько раз. С его помощью вы получите работающий сервер в течение нескольких минут.
Настройка OpenVPN сервера в Linux
В этой статье, в качестве системы для примера мы будем использовать операционную систему CentOS, но операции не будут отличаться в других дистрибутивах. Сначала скачайте сам скрипт:
wget https://git.io/vpn -O openvpn-install.sh
Затем запустите скрипт от имени суперпользователя с помощью такой команды:
Дальше скрипт задаст несколько вопросов по настройкам OpenVPN. Сначала нужно указать точный ip адрес VPS, на котором будет запущен OpenVPN, именно на этом адресе программа будет слушать соединения:
Затем выберите протокол, который вы хотите использовать. Например, если я хочу использовать TCP то нужно выбрать 2:
Затем введите номер порта, на котором будет слушать программа, можно оставить значение по умолчанию:
Выберите сервера DNS, которые нужно использовать, мне, например, нравятся сервера от Google:
Введите имя клиента, для которого будут подписаны сертификаты на доступ:
Дальше нажмите Enter, и подтвердите установку OpenVPN. Программа сама установит нужные пакеты в вашем дистрибутиве, а затем подпишет все необходимые сертификаты, запустит сервер openvpn и даже добавит его в автозагрузку systemd:
Последний шаг, это утилита спросит есть ли у вашего сервера дополнительный внешний ip адрес. Это может быть полезно, если вы используете NAT, и для доступа к серверу применяете какой-либо туннель. В других случаях этот пункт можно пропустить, для VPS точно пропускаем.
Теперь установка и настройка OpenVPN сервера Linux завершена. Конфигурационный файл для клиента сохранен по адресу /root/sergiy-pc.ovpn, может иметь и другое имя, в зависимости от того, какое имя вы дали клиенту. Самое интересное, что для того чтобы добавить новых клиентов, вам просто достаточно запустить скрипт еще раз. Осталось только скопировать полученный файл клиенту, для этого можно на клиентском компьютере выполнить scp:
scp root@адрес_сервера:/root/sergiy-pc.ovpn /etc/openvpn/
Настройка клиента OpenVPN
Вы можете настроить OpenVPN на клиентской машине как захотите, например, с помощью NetworkManager. Но мы рассмотрим ручной вариант. Сначала установите саму программу. Установка OpenVPN Linux Ubuntu выполняется командой:
sudo apt install openvpn
sudo yum install openvpn
Теперь для подключения к нашему серверу используем полученный файл:
openvpn —config /etc/openvpn/client.ovpn
Вы можете использовать команду ip addr чтобы проверить ip адрес интерфейса OpenVPN — tun0:
Как видите, OpenVPN автоматически выдал IP вашему компьютеру, теперь можете проверить подключение к этому серверу с помощью ping:
Вот и все, ваша сеть готова к работе.
Выводы
Пять минут и настройка OpenVPN Linux завершена, а не подключение следующего клиента уйдет еще меньше. Этот метод не специфичен для RPM систем и может использоваться также в DEB системах, таких как Ubuntu или Debian. Если у вас остались вопросы, спрашивайте в комментариях!
Полная настройка OpenVPN:
Источник
Installing openvpn on linux
OpenVPN installer for Debian, Ubuntu, Fedora, CentOS, Arch Linux, Oracle Linux, Rocky Linux and AlmaLinux.
This script will let you setup your own secure VPN server in just a few seconds.
You can also check out wireguard-install, a simple installer for a simpler, safer, faster and more modern VPN protocol.
First, get the script and make it executable:
You need to run the script as root and have the TUN module enabled.
The first time you run it, you’ll have to follow the assistant and answer a few questions to setup your VPN server.
When OpenVPN is installed, you can run the script again, and you will get the choice to:
- Add a client
- Remove a client
- Uninstall OpenVPN
In your home directory, you will have .ovpn files. These are the client configuration files. Download them from your server and connect using your favorite OpenVPN client.
If you have any question, head to the FAQ first. Please read everything before opening an issue.
PLEASE do not send me emails or private messages asking for help. The only place to get help is the issues. Other people may be able to help and in the future, other users may also run into the same issue as you. My time is not available for free just for you, you’re not special.
It’s also possible to run the script headless, e.g. without waiting for user input, in an automated manner.
A default set of variables will then be set, by passing the need for user input.
If you want to customise your installation, you can export them or specify them on the same line, as shown above.
- APPROVE_INSTALL=y
- APPROVE_IP=y
- IPV6_SUPPORT=n
- PORT_CHOICE=1
- PROTOCOL_CHOICE=1
- DNS=1
- COMPRESSION_ENABLED=n
- CUSTOMIZE_ENC=n
- CLIENT=clientname
- PASS=1
If the server is behind NAT, you can specify its endpoint with the ENDPOINT variable. If the endpoint is the public IP address which it is behind, you can use ENDPOINT=$(curl -4 ifconfig.co) (the script will default to this). The endpoint can be an IPv4 or a domain.
Other variables can be set depending on your choice (encryption, compression). You can search for them in the installQuestions() function of the script.
Password-protected clients are not supported by the headless installation method since user input is expected by Easy-RSA.
The headless install is more-or-less idempotent, in that it has been made safe to run multiple times with the same parameters, e.g. by a state provisioner like Ansible/Terraform/Salt/Chef/Puppet. It will only install and regenerate the Easy-RSA PKI if it doesn’t already exist, and it will only install OpenVPN and other upstream dependencies if OpenVPN isn’t already installed. It will recreate all local config and re-generate the client file on each headless run.
Headless User Addition
It’s also possible to automate the addition of a new user. Here, the key is to provide the (string) value of the MENU_OPTION variable along with the remaining mandatory variables before invoking the script.
The following Bash script adds a new user foo to an existing OpenVPN configuration
- Installs and configures a ready-to-use OpenVPN server
- Iptables rules and forwarding managed in a seamless way
- If needed, the script can cleanly remove OpenVPN, including configuration and iptables rules
- Customisable encryption settings, enhanced default settings (see Security and Encryption below)
- OpenVPN 2.4 features, mainly encryption improvements (see Security and Encryption below)
- Variety of DNS resolvers to be pushed to the clients
- Choice to use a self-hosted resolver with Unbound (supports already existing Unbound installations)
- Choice between TCP and UDP
- NATed IPv6 support
- Compression disabled by default to prevent VORACLE. LZ4 (v1/v2) and LZ0 algorithms available otherwise.
- Unprivileged mode: run as nobody / nogroup
- Block DNS leaks on Windows 10
- Randomised server certificate name
- Choice to protect clients with a password (private key encryption)
- Many other little things!
The script supports these OS and architectures:
i386 | amd64 | armhf | arm64 | |
---|---|---|---|---|
Amazon Linux 2 | ❔ | ✅ | ❔ | ❔ |
Arch Linux | ❔ | ✅ | ❔ | ✅ |
CentOS 7 | ✅ | ✅ | ✅ | ✅ |
CentOS 8 | ❌ | ✅ | ❌ | ✅ |
Debian >= 9 | ✅ | ✅ | ✅ | ✅ |
Fedora >= 27 | ❔ | ✅ | ❔ | ❔ |
Ubuntu 16.04 | ✅ | ✅ | ❌ | ❌ |
Ubuntu >= 18.04 | ✅ | ✅ | ✅ | ✅ |
Oracle Linux 8 | ❌ | ✅ | ❌ | ❔ |
Rocky Linux 8 | ❔ | ✅ | ❔ | ❔ |
AlmaLinux 8 | ❌ | ✅ | ❌ | ❔ |
- It should work on Debian 8+ and Ubuntu 16.04+. But versions not in the table above are not officially supported.
- The script requires systemd .
- The script is regularly tested against amd64 only.
This script is based on the great work of Nyr and its contributors.
Since 2016, the two scripts have diverged and are not alike anymore, especially under the hood. The main goal of the script was enhanced security. But since then, the script has been completely rewritten and a lot a features have been added. The script is only compatible with recent distributions though, so if you need to use a very old server or client, I advise using Nyr’s script.
Q: Which provider do you recommend?
A: I recommend these:
- Vultr: Worldwide locations, IPv6 support, starting at $3.50/month
- Hetzner: Germany, IPv6, 20 TB of traffic, starting at €3/month
- Digital Ocean: Worldwide locations, IPv6 support, starting at $5/month
- PulseHeberg: France, unlimited bandwidth, starting at €3/month
Q: Which OpenVPN client do you recommend?
A: If possible, an official OpenVPN 2.4 client.
Q: Am I safe from the NSA by using your script?
A: Please review your threat models. Even if this script has security in mind and uses state-of-the-art encryption, you shouldn’t be using a VPN if you want to hide from the NSA.
Q: Is there an OpenVPN documentation?
A: Yes, please head to the OpenVPN Manual, which references all the options.
One-stop solutions for public cloud
Solutions that provision a ready to use OpenVPN server based on this script in one go are available for:
We use shellcheck and shfmt to enforce bash styling guidelines and good practices. They are executed for each commit / PR with GitHub Actions, so you can check the configuration here.
Security and Encryption
OpenVPN’s default settings are pretty weak regarding encryption. This script aims to improve that.
OpenVPN 2.4 was a great update regarding encryption. It added support for ECDSA, ECDH, AES GCM, NCP and tls-crypt.
If you want more information about an option mentioned below, head to the OpenVPN manual. It is very complete.
Most of OpenVPN’s encryption-related stuff is managed by Easy-RSA. Defaults parameters are in the vars.example file.
By default, OpenVPN doesn’t enable compression. This script provides support for LZ0 and LZ4 (v1/v2) algorithms, the latter being more efficient.
However, it is discouraged to use compression since the VORACLE attack makes use of it.
OpenVPN accepts TLS 1.0 by default, which is nearly 20 years old.
With tls-version-min 1.2 we enforce TLS 1.2, which the best protocol available currently for OpenVPN.
TLS 1.2 is supported since OpenVPN 2.3.3.
OpenVPN uses an RSA certificate with a 2048 bits key by default.
OpenVPN 2.4 added support for ECDSA. Elliptic curve cryptography is faster, lighter and more secure.
This script provides:
- ECDSA: prime256v1 / secp384r1 / secp521r1 curves
- RSA: 2048 / 3072 / 4096 bits keys
It defaults to ECDSA with prime256v1 .
OpenVPN uses SHA-256 as the signature hash by default, and so does the script. It provides no other choice as of now.
By default, OpenVPN uses BF-CBC as the data channel cipher. Blowfish is an old (1993) and weak algorithm. Even the official OpenVPN documentation admits it.
The default is BF-CBC, an abbreviation for Blowfish in Cipher Block Chaining mode.
Using BF-CBC is no longer recommended, because of its 64-bit block size. This small block size allows attacks based on collisions, as demonstrated by SWEET32. See https://community.openvpn.net/openvpn/wiki/SWEET32 for details. Security researchers at INRIA published an attack on 64-bit block ciphers, such as 3DES and Blowfish. They show that they are able to recover plaintext when the same data is sent often enough, and show how they can use cross-site scripting vulnerabilities to send data of interest often enough. This works over HTTPS, but also works for HTTP-over-OpenVPN. See https://sweet32.info/ for a much better and more elaborate explanation.
OpenVPN’s default cipher, BF-CBC, is affected by this attack.
Indeed, AES is today’s standard. It’s the fastest and more secure cipher available today. SEED and Camellia are not vulnerable to date but are slower than AES and relatively less trusted.
Of the currently supported ciphers, OpenVPN currently recommends using AES-256-CBC or AES-128-CBC. OpenVPN 2.4 and newer will also support GCM. For 2.4+, we recommend using AES-256-GCM or AES-128-GCM.
AES-256 is 40% slower than AES-128, and there isn’t any real reason to use a 256 bits key over a 128 bits key with AES. (Source: 1,2). Moreover, AES-256 is more vulnerable to Timing attacks.
AES-GCM is an AEAD cipher which means it simultaneously provides confidentiality, integrity, and authenticity assurances on the data.
The script supports the following ciphers:
And defaults to AES-128-GCM .
OpenVPN 2.4 added a feature called «NCP»: Negotiable Crypto Parameters. It means you can provide a cipher suite like with HTTPS. It is set to AES-256-GCM:AES-128-GCM by default and overrides the —cipher parameter when used with an OpenVPN 2.4 client. For the sake of simplicity, the script set both the —cipher and —ncp-cipher to the cipher chosen above.
OpenVPN 2.4 will negotiate the best cipher available by default (e.g ECDHE+AES-256-GCM)
The script proposes the following options, depending on the certificate:
- ECDSA:
- TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256
- TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384
- RSA:
- TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256
- TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384
It defaults to TLS-ECDHE-*-WITH-AES-128-GCM-SHA256 .
Diffie-Hellman key exchange
OpenVPN uses a 2048 bits DH key by default.
OpenVPN 2.4 added support for ECDH keys. Elliptic curve cryptography is faster, lighter and more secure.
Also, generating a classic DH keys can take a long, looong time. ECDH keys are ephemeral: they are generated on-the-fly.
The script provides the following options:
- ECDH: prime256v1 / secp384r1 / secp521r1 curves
- DH: 2048 / 3072 / 4096 bits keys
It defaults to prime256v1 .
HMAC digest algorithm
From the OpenVPN wiki, about —auth :
Authenticate data channel packets and (if enabled) tls-auth control channel packets with HMAC using message digest algorithm alg. (The default is SHA1 ). HMAC is a commonly used message authentication algorithm (MAC) that uses a data string, a secure hash algorithm, and a key, to produce a digital signature.
If an AEAD cipher mode (e.g. GCM) is chosen, the specified —auth algorithm is ignored for the data channel, and the authentication method of the AEAD cipher is used instead. Note that alg still specifies the digest used for tls-auth.
The script provides the following choices:
It defaults to SHA256 .
tls-auth and tls-crypt
From the OpenVPN wiki, about tls-auth :
Add an additional layer of HMAC authentication on top of the TLS control channel to mitigate DoS attacks and attacks on the TLS stack.
In a nutshell, —tls-auth enables a kind of «HMAC firewall» on OpenVPN’s TCP/UDP port, where TLS control channel packets bearing an incorrect HMAC signature can be dropped immediately without response.
Encrypt and authenticate all control channel packets with the key from keyfile. (See —tls-auth for more background.)
Encrypting (and authenticating) control channel packets:
- provides more privacy by hiding the certificate used for the TLS connection,
- makes it harder to identify OpenVPN traffic as such,
- provides «poor-man’s» post-quantum security, against attackers who will never know the pre-shared key (i.e. no forward secrecy).
So both provide an additional layer of security and mitigate DoS attacks. They aren’t used by default by OpenVPN.
tls-crypt is an OpenVPN 2.4 feature that provides encryption in addition to authentication (unlike tls-auth ). It is more privacy-friendly.
The script supports both and uses tls-crypt by default.
You can say thanks if you want!
Many thanks to the contributors and Nyr’s original work.
Источник