Tag: data encryption

Script to connect and disconnect from OpenVPN depending on server availability

Task:

Branch subnets are connected via OpenVPN. All clients connect to the server and routes to the Internet are set through the OpenVPN server. Everything works, but there is a problem. If the OpenVPN server for some reason loses Internet connection, then all other branches also lose Internet access, because the traffic does not go through its gateway, but through the OpenVPN server. Is there any way to write a script to:

1. If there was no connection to the OpenVPN server, the routes were restored and worked through their own gateway.

2. Once every 2-3 minutes the client would try to connect to the OpenVPN server.

3. When the connection is restored, the routes would be registered again through the OpenVPN server.

Solution:

In theory, it is quite possible to write a script in Bash (for Linux) or PowerShell (for Windows) that would ping the OpenVPN server and if the server is online connecting to it or if the connection is already present, it would do nothing. And if the OpenVPN server is offline, then it would disconnect from it or do nothing if the server is already offline. On Linux, such a script can be added to startup and then run regularly using Systemd timers or Cron. In Windows, too, this can be solved using the Windows Task Scheduler.

But, IMHO, this is a radically wrong approach. It is necessary to strive to ensure that the OpenVPN server is always online. Because for some reason it is needed in the work of users if they connect to it, right? And if so, then when users disconnect from OpenVPN, there will be failures in connecting to local resources.

And nevertheless, here are examples of scripts.

For Windows, the script is written in PowerShell, create the vpn.ps1 file and copy it into it (replace the IP address of the OpenVPN server and the path to the configuration file with yours):

# OpenVPN server IP address
$openvpnIP='185.117.153.79'
# path to the configuration file for connecting the client to the OpenVPN server
$openvpnFILE='C:\Users\MiAl\client1.ovpn'

if (Test-Connection -TargetName $openvpnIP -IPv4 -Count 1 -Quiet -TimeoutSeconds 1)
{
	'OpenVPN server is up'
	if (Get-Process | Where-Object { $_.Name -eq "openvpn" })
	{
		'OpenVPN connection is active.  Nothing to do'
	}
		else
	{
		Write-Warning 'No OpenVPN connections, trying to connect...'
		 & "C:\Program Files\OpenVPN\bin\openvpn.exe" --config $openvpnFILE &
	}
}
else
{
	Write-Warning 'OpenVPN server is down'
	if (Get-Process | Where-Object { $_.Name -eq "openvpn" })
	{
		'OpenVPN connection is active, let us kill it'
		Get-Process | Where-Object { $_.Name -eq "openvpn" } | Select-Object -First 1 | Stop-Process
	}
	else
	{
		Write-Warning 'No OpenVPN connections. Nothing to do'
	}
}

Check like this:

.\vpn.ps1

The OpenVPN server is online, so the script connects to it and does nothing on subsequent checks. Checking the client's IP shows that Internet access is really through OpenVPN:

OpenVPN is offline, so the script disconnects from it. On subsequent checks, the script does nothing until the OpenVPN server is available. When OpenVPN is online again, a connection is made to it.

Use Windows Task Manager to run your script like this:

powershell -File vpn.ps1 -WindowStyle Hidden

Furthermore create the script that it runs under a specific user account and not only when that user is logged on. Otherwise you'll see a console window.

Sample script for Linux – create a vpn.sh file and copy into it:

#!/bin/bash

# OpenVPN server IP address
openvpnIP='185.117.153.79'
# path to the configuration file for connecting the client to the OpenVPN server
openvpnFILE='/home/mial/bin/OpenVPNassistent-конфигурации/configs/client1.ovpn'

isOpenVPNActive=`pgrep openvpn`

timeout 1 ping -c 1 $openvpnIP > /dev/null;
if [ $? -eq 0 ]; then
	echo 'OpenVPN server is up'
	if [ -z "$isOpenVPNActive" ]; then
		echo 'No OpenVPN connections, trying to connect.'
		sudo openvpn "$openvpnFILE" &
	else
		echo 'OpenVPN connection is active. Nothing to do'	 
	fi	
else
	echo 'OpenVPN server is down'
	if [ -z "$isOpenVPNActive" ]; then
		echo 'No OpenVPN connections. Nothing to do.'
	else
		echo 'OpenVPN connection is active, let us kill it.'
		kill "$isOpenVPNActive"
	fi 
fi

Run like this:

sudo bash vpn.sh

The OpenVPN server is online, so the script connects to it and does nothing on subsequent checks. Checking the client's IP shows that Internet access is really through OpenVPN. OpenVPN is offline, so the script disconnects from it. On subsequent checks, the script does nothing until the OpenVPN server is available. When OpenVPN is online again, a connection is made to it.

To run regularly, use systemd's .timer or cron.

See also:

How to manage VPN Settings in GNOME 3

A popular example of a Linux distribution using GNOME 3 is Ubuntu.

How to add OpenVPN connection settings to GNOME 3

To add an OpenVPN connection, click on the network connection icon and expand the connections section.

Select “Wired Settings”:

You will find yourself in the OS settings. On the “Network” tab, you can add a new VPN connection or manage existing ones. Click the plus sign (+) to add a new one.

You can enter the data manually, or import the OpenVPN connection settings from the .ovpn file.

With manual configuration, you do not need to change anything in the “IPv4” and “IPv6” tabs. Some of the settings are located on the “Identity” tab, to access other settings, click the “Advanced” button:

How to connect to OpenVPN on GNOME 3

You can enable OpenVPN connection by clicking on the network connections button, then selecting the desired VPN connection.

You can also go to Network Settings and enable the selected OpenVPN connection there.

How to change OpenVPN connection settings in GNOME 3

To edit VPN connections, click on the network connections button, then expand the VPN list and select “VPN Settings”.

Select the connection you want to change and press the gear.

How to remove OpenVPN connection in GNOME 3

To remove an OpenVPN connection, go to its settings, as shown just above, and click the “Remove VPN” button.

How to manage VPN Settings in Xfce

Popular distributions with Xfce include Kali Linux and Xubuntu.

In Xfce, networks are managed in the “Network Connections” window.

How to add OpenVPN connection settings to Xfce

There are two ways to add a new OpenVPN connection:

1) Right-click on the network connection icon and select “Edit Connections”:

In the Network Connections, click the plus sign (+).

2) Or left-click on the network connection icon and select “VPN Connections”→ “Add a VPN Connection”.

Select your preferred VPN connection type.

To import a VPN connection from a file, select “Import a saved VPN configuration”.

Click the “Create” button and specify the settings file.

With manual configuration, you do not need to change anything on the “General”, “Proxy”, “IPv4 Settings”, and “IPv6 Settings” tabs. Some of the settings are located on the “VPN” tab, to access other settings, click the “Advanced” button.

How to connect to OpenVPN in Xfce

To connect to OpenVPN, left-click on the network connection icon and select “VPN Connections” and then select the desired connection.

If the connection is successful, a check mark will appear next to the VPN connection name.

How to change or remove OpenVPN connection settings in Xfce

To add, change and remove VPN connections, go to Network Connections, for this, right-click on the network connection icon and select “Edit Connections”.

How to manage VPN Settings in Cinnamon

The Cinnamon desktop environment is primarily characteristic of Linux Mint.

Network Connections and Network Settings in Cinnamon

When you click on the network connection icon (its appearance depends on whether you are using a wired or wireless connection), two options will be available to manage networks:

  • Network Settings – featured by Cinnamon (therefore, it is present only in this desktop environment)
  • Network Connections – featured by NetworkManager (hence, it is present in any distribution with NetworkManager)

In general, these settings allow you to do the same things: add, edit and remove network connections.

Network Settings contains a list of Wi-Fi networks available for connection, as well as a list of OpenVPN settings, proxies, wired connections. In Network Settings, you can activate a particular network connection.

Network Connections does not show Wi-Fi networks available for connection, but it stores the settings of the networks to which the computer has ever connected.

Managing OpenVPN Connections in Network Settings

To remove an OpenVPN connection, select it and click the minus sign (-).

The connection will be dropped without confirmation.

Click the plus sign (+) to add an OpenVPN connection.

You will be presented with 2 options:

  • OpenVPN (compatible with the OpenVPN server) – you will need to enter the settings manually and specify the certificate files
  • Import from file – import settings from an .ovpn file

With manual configuration, you don't need to change anything in the “IPv4” and “IPv6” tabs. Some of the settings are located on the “Identity” tab, to access other settings, click the “Advanced” button:

To edit an OpenVPN connection, select it and click the gear icon.

Some of the settings are located on the “Identity” tab.

To access other settings, click the “Advanced” button.

Managing OpenVPN Connections in Network Connections

To remove an OpenVPN connection, select it and click the minus sign (-).

Click the plus sign (+) to add an OpenVPN connection.

In the drop-down list, you will have many options available, 2 of them are related to OpenVPN:

  • OpenVPN – you will need to enter the settings manually and specify the certificate files
  • Import a saved VPN configuration

With manual configuration, you do not need to change anything on the “General”, “Proxy”, “IPv4 Settings”, and “IPv6 Settings” tabs. Some of the settings are located on the “VPN” tab, to access other settings, click the “Advanced” button.

To edit an OpenVPN connection, select it and click the gear icon.

Connecting to OpenVPN server

You can add multiple OpenVPN connections and enable any of them depending on your needs. You can enable them as in the main NetworkManager panel – click on the selected connection:

You can also enable VPN connections in Network Settings, to do this, select the desired VPN connection and click the switch:

Simultaneous use of multiple OpenVPNs on one server

You can simultaneously use several OpenVPN processes on the same server, while they will work on different ports and provide separate virtual private networks that do not overlap with each other.

Multiple instances of OpenVPN are provided out of the box, but additional configuration is required.

1. OpenVPN services must use different ports

All OpenVPN services must use a free port. Remember that the same UDP and TCP port numbers are different ports, that is, you can use the same port number in two instances of OpenVPN, provided that one of them is a UDP port and the other is a TCP port.

If two OpenVPN services use the same port, then the OpenVPN instance that is started first will work without error, and the second instance will not start due to the error “TCP/UDP: Socket bind failed on local address [AF_INET][undef]:…: Address already in use (errno=98)”, for example:

2021-11-02 09:26:50 us=736094 TCP/UDP: Socket bind failed on local address [AF_INET][undef]:53: Address already in use (errno=98)
2021-11-02 09:26:50 us=736216 Exiting due to fatal error

2. Range of addresses of the virtual private network

By default, a range of IP addresses for a virtual private network is specified in the server configuration file, for example:

server 10.8.0.0 255.255.255.0

Additional instances of the OpenVPN service must use different ranges. For example, for the second service, you can specify the following range:

server 10.8.1.0 255.255.255.0

For the third service, you can specify the following range of IP addresses, and so on:

server 10.8.2.0 255.255.255.0

3. Traffic routing for all virtual private networks

The section “Enable traffic routing on the OpenVPN server” shows how to enable NAT for VPN traffic so that clients can make connections to the Internet. The example in the above section shows how to configure routing for traffic from the 10.8.1.0/24 subnet. Since additional instances of the OpenVPN service use different subnets (for example, 10.8.1.0/24), in order for the clients of these virtual networks to access the Internet, you must configure routing for each of these networks.

An example of the original contents of the /root/bin/vpn_route.sh file:

#!/bin/sh

# specify the name of the interface, otherwise the script will try to select it automatically
#DEV='eth0'
DEV='ens3'
PRIVATE=10.8.0.0/24
 
if [ -z "$DEV" ]; then
	DEV="$(ip route | grep default | head -n 1 | awk '{print $5}')"
fi
# Turn forwarding packets on from the tunnel interface
# they got to the external interface
sysctl net.ipv4.ip_forward=1
# Make sure iptables do not block redirected traffic:
iptables -I FORWARD -j ACCEPT
# Network Address Translation (NAT) for packets coming from the tunnel
# When forwarding is enabled, packets are forwarded by default.
# with the original address unchanged, that is, in our case 10.8.0.*
# such packages are either deleted at the ISP gateway, or even if they are
# go to the destination, the answer never finds a way back.
# These private addresses are not routed to the Internet.
#
# The solution is Network Address Translation (NAT) of outgoing traffic,
# i.e. replace private 10.8.0.* address with the public IP address of the VPN server.
# This will allow responses to reach the VPN server,
# and there they will be sent back to the tunnel.
iptables -t nat -I POSTROUTING -s $PRIVATE -o $DEV -j MASQUERADE

The file /root/bin/vpn_route.sh which has added NAT for subnets 10.8.1.0/24, 10.8.2.0/24, and 10.8.3.0/24:

#!/bin/sh
 
DEV='ens3'
PRIVATE=10.8.0.0/24
 
if [ -z "$DEV" ]; then
	DEV="$(ip route | grep default | head -n 1 | awk '{print $5}')"
fi

sysctl net.ipv4.ip_forward=1

iptables -I FORWARD -j ACCEPT

iptables -t nat -I POSTROUTING -s $PRIVATE -o $DEV -j MASQUERADE

iptables -t nat -I POSTROUTING -s 10.8.1.0/24 -o $DEV -j MASQUERADE

iptables -t nat -I POSTROUTING -s 10.8.2.0/24 -o $DEV -j MASQUERADE

To check the NAT settings, run the command

iptables -L -t nat

4. Configuring local static addresses

If you used the section “How to make static IPs for OpenVPN clients” and added entries like “ifconfig-push 10.8.0.10 255.255.255.0” to the file “/etc/openvpn/ccd/client1”, then you need to use different client names for the second and subsequent OpenVPN networks as they use different VPN IP ranges.

5. Starting and adding the second and subsequent OpenVPN services to startup

Note that with systemctl you can use a command like

openvpn-server@<configuration>.service

where <configuration> is a configuration file located in the /etc/openvpn/server/ folder, but without the .conf extension

For example, the second configuration file for the second instance of the OpenVPN service is placed in the /etc/openvpn/server/server-tcp.conf file, then the program for starting the service is as follows:

sudo systemctl start openvpn-server@server-tcp.service

Checking the status of the service with the server-tcp.conf configuration file:

systemctl status openvpn-server@server-tcp.service

View OpenVPN service errors with server-tcp.conf config file:

journalctl -xeu openvpn-server@server-tcp.service

Add service to startup:

sudo systemctl enable openvpn-server@server-tcp.service

See also:

Comparison of performance (data transfer rate) of OpenVPN over UDP and TCP

The previous article showed how to use OpenVPN with TCP instead of the default UDP. It is also known that the use of the TCP protocol is not recommended because, due to the “overhead” of the TCP transport protocol, less payload will be transmitted, since part of the channel will be occupied by the transmission of overhead information necessary to control the integrity of transmitted packets. But how exactly will switching from UDP to TCP affect the performance of the OpenVPN server and the speed of receiving and sending data? This article is devoted to the answer to this question.

My internet connection speed without using OpenVPN:

My internet connection speed using OpenVPN over UDP:

My internet connection speed using OpenVPN over TCP:

As you can see, the speed loss when migrating from UDP to TCP is quite significant. The difference in speed between the absence of OpenVPN and OpenVPN over UDP is negligible – in fact, in both cases, the speed is practically limited by the maximum bandwidth of my network.

See also:

How to use OpenVPN with TCP protocol

By default, OpenVPN uses UDP and it is officially recommended to use it. However, TCP also works great with OpenVPN and you can use it if needed. Theoretically, the TCP protocol has more “overhead”, that is, some part of the transmitted data will not carry the payload, but is only necessary for the normal operation of TCP, which monitors the safety and integrity of transmitted packets.

In my case, the need to add TCP support arose due to the fact that with some ISPs OpenVPN on the UDP protocol could not connect due to an error (the error will be discussed later), but it worked fine on the TCP protocol.

To configure OpenVPN to work with TCP, you need to know the following points:

1. The protocol must be specified explicitly

In the settings of the configuration files, instead of the line

;proto tcp

use on the server the line

proto tcp-server

and on the client the line

proto tcp-client

For reference: UDP protocol on both the server and the client is denoted the same way:

proto udp

2. The TCP protocol must be specified in the configuration files of both the server and the client

Protocol settings are not transferred from the server and must be explicitly specified not only on the server itself, but also for each client in the configuration file.

3. Do not use the explicit-exit-notify option

In the server config file, don't use the setting (just remove this line):

explicit-exit-notify 1

Otherwise, you will encounter the error:

Options error: --explicit-exit-notify can only be used with --proto udp

4. The port must be free

This applies equally to how OpenVPN works with UDP and TCP: the selected port must be free, otherwise you will encounter the error “TCP/UDP: Socket bind failed on local address [AF_INET][undef]:…: Address already in use (errno=98)”, for example:

2021-11-02 09:26:50 us=736094 TCP/UDP: Socket bind failed on local address [AF_INET][undef]:53: Address already in use (errno=98)
2021-11-02 09:26:50 us=736216 Exiting due to fatal error

See also: 

How to change configuration files when migrating from OpenVPN 2.4.* to OpenVPN 2.5.*

As of fall 2021, OpenVPN has moved to the new major branch 2.5.* for almost a year. If you were slow to update, now the new branch can be considered time-tested. However, if you are upgrading from the 2.4 branch, you may need to adjust the configuration files.

1. In the server and client configuration files, replace the line

cipher AES-256-CBC

with

data-ciphers AES-256-GCM:AES-128-GCM

2. If you are using the TCP protocol (which is not recommended), then instead of the line

;proto tcp

use the line on the server

proto tcp-server

and the line on the client

proto tcp-client

The UDP protocol is the same on the server and on the client:

proto udp

3. When configuring static IP addresses within a virtual private network, the following entry is now used:

ifconfig-push client_IP SUBNET_MASK

for example:

ifconfig-push 10.8.0.10 255.255.255.0

See the section “How to make static IPs for OpenVPN clients” for details.

See also: 

How to install Kali Linux with encrypted user’s home folder (manual partitioning)

If the above automatic disk layout template with encryption of the home folder does not suit you, then you can configure disk layout manually, below is shown how to do it.

With manual marking, remember that for a normal installation you need at least two partitions:

  • EFI – 200 Megabytes is enough
  • / (root of the filesystem) – this is where the OS is installed. If there are no other partitions, then user files will be stored here.

In this example, in addition to the two necessary ones, we will create another partition and encrypt it, this partition will be mounted on the /home path.

Go to the page https://www.kali.org/get-kali/, in the Bare Metal section download the installation image.

Using a cross-platform program, Etcher writes an image to a USB flash drive.

Let's dwell directly on the disk layout, since the rest of the installation steps are identical.

When you come to the disk partitioning, then select “Manual”.

Select the drive where the system will be installed.

There is no partition table on the media, we agree to create it, that is, select “Yes”.

We select an unoccupied area (“FREE SPACE”).

Select “Create a new partition”.

The first partition will be EFI, 100-200 Megabytes are enough for it, allocate 200 Megabytes with a margin.

Choose “Beginning”.

In the “Use as” field, select “EFI System Partition”. Then click “Done setting up the partition”.

Select “FREE SPACE” again.

Choose “Create a new partition”.

Select the size of the partition. This partition will be the root one, OS files will be installed on it and programs will be installed here. It is not recommended to make this partition less than 20 Gigabytes.

We choose “Beginning”.

In the “Use as” field, select “Ext4 journaling file system”. Select “/” for “Mount point”. Then click “Done setting up the partition”.

Now let's move on to creating an encrypted partition. Select “Configure Encrypted Volumes”.

We are warned that in order to start creating an encrypted one, the current partition scheme (the two partitions that we have just created) must be written to the disk – these changes cannot be reversed. Select “Yes”.

Choose “Create encrypted volume”.

We choose where exactly this partition will be placed. Be especially careful if you have multiple drives. In the screenshot, the free space of the only disk is selected. But if you do not want to use all the free space, then first create a partition of the desired size and select it here. For this partition, in the “Use as” field, select “not use”.

We select “Done setting up the partition”.

Again, you need to save the current partitioning scheme to disk. Select “Yes”.

I only need one partition, so I choose “Finish”.

We are warned that the selected partition will be overwritten with random data and information from it will be lost. If everything is alright, then select “Yes”.

Enter the password to decrypt the partition.

So far we have only created an encrypted partition that has no volumes or mount points. This is all configurable in LVM.

Go to “Configure the Logical Volume Manager”.

Again, you need to write down the current partition scheme, again “Yes”.

Quite a bit of theory:

LVM manages three concepts:

  • Volume groups
  • Physical volumes
  • Logical volumes

A volume group is a named collection of physical and logical volumes. Typical systems only need one volume group to contain all the physical and logical volumes on the system, and I like to call my group by the name of the machine. Physical volumes correspond to disks; they are block devices that provide storage space for logical volumes. Logical volumes correspond to partitions: they contain the file system. However, unlike partitions, logical volumes are named, not numbers, they can span multiple disks, and do not have to be physically contiguous.

In this step we are creating a volume group, select “Create volume group”.

Come up with a name – you can use the name of your system, but I named it in accordance with the purpose.

Select the device for the new volume group. This device is the encrypted partition created in the previous step.

You need to write down the current partition scheme (“Yes”).

Now choose “Create logical volume”.

Choose a group – it is one.

Name the volume – the name can be arbitrary, but it is in your best interest to use meaningful name.

Specify the size of the volume.

One volume is enough for me, so I choose “Finish”.

Now you can observe the created volume, but it is not used in any way and no file system is selected for it. Click on the volume record.

In the “Use as” field, select “Ext4 journaling file system”.

Select “/home” for “Mount point”. Then click “Done setting up the partition”.

Finish partitioning the disk, select “Finish partitioning and write changes to disk” → “Continue”.

I am warned that I have not created a swap partition – I have 32 GB of RAM, I do not need a wap partition, so I choose “No”.

We are once again warned that the data will be written to the disk and the information on it will be lost, select “Yes”.

Further installation steps are identical to the first example.

If everything is done correctly, you will be prompted for a password when you turn on the computer.

You can make sure that the list of block devices is exactly as we intended it.

How to install Kali Linux with encrypted user’s home folder (auto-partitioning)

The installer has a template for encrypting the user's home folder and it is perfect for novice users – the default settings are quite acceptable, the setup is very simple.

The markup template has the following parameters:

  • EFI partition – 500 MB
  • /boot partition – 500 MB
  • / (root) partition – 30 GB
  • swap (swap partition) – 1 GB
  • /home partition – all remaining space

Go to the page https://www.kali.org/get-kali/, in the Bare Metal section download the installation image.

Using a cross-platform program, Etcher writes an image to a USB flash drive.

Let's dwell directly on the disk layout, since the rest of the installation steps are identical.

When you come to the partitioning of the disks, then select “Guided - use entire disk and set up encrypted LVM”.

Select the drive where the system will be installed.

Select “Separate /home partition”.

We are warned that in order to start creating an encrypted one, the current partition scheme (the two partitions that we have just created) must be written to the disk – these changes cannot be reversed. Select “Yes”.

The partition to be encrypted is filled with random data – this process takes time.

Enter the password twice that will encrypt the partition.

For automatic partitioning, you can use all or part of the volume group size. If you have little idea about the possibilities of LVM, then just use the entire available size.

An overview of the configured partitions. In this example, the root partition is 30 GB and the /home directory is 224.6 GB.

Click “Finish partitioning and write changes to disk” → “Continue”.

Agree to write data to disk by selecting “Yes”.

Loading...
X