setup openvpn on ubuntu 20.04.

Certificate Server Setup

Ensure that the CA Server is a standalone system. It will only be used to import, sign, and revoke certificate requests. It should not run any other services, and ideally it will be offline or completely shut down when you are not actively working with your CA.

I used version below:

finuks@VM-16-11-ubuntu:~/client-configs$ dpkg-query --list | grep easy-rsa
ii  easy-rsa                              3.0.6-1                           all          Simple shell based CA utility

Installing Easy-RSA

easy-rsa is a Certificate Authority management tool that you will use to generate a private key, and public root certificate, which you will then use to sign requests from clients and servers that will rely on your CA.

sudo apt update
sudo apt install easy-rsa

Create User for CA

Use the adduser command to add a new user to your system:

sudo adduser ca

Adding the User to the sudo Group

usermod -aG sudo ca

To test that the new sudo permissions are working, first use the su command to switch to the new user account:

su - ca

you can list the contents of the /root directory, which is normally only accessible to the root user:

sudo ls -la /root

Preparing a Public Key Infrastructure Directory

it is time to create a skeleton Public Key Infrastructure (PKI) on the CA Server.Make sure that you do not use sudo to run any of the following commands, since your normal user should manage and interact with the CA without elevated privileges.

mkdir ~/easy-rsa

We’ll use this directory to create symbolic links pointing to the easy-rsa package files that we’ve installed in the previous step. These files are located in the /usr/share/easy-rsa folder on the CA Server. Create the symlinks with the ln command:

ln -s /usr/share/easy-rsa/* ~/easy-rsa/

NOTE:While other guides might instruct you to copy the easy-rsa package files into your PKI directory, this tutorial adopts a symlink approach. As a result, any updates to the easy-rsa package will be automatically reflected in your PKI’s scripts.

To restrict access to your new PKI directory, ensure that only the owner can access it using the chmod command:

chmod 700 /home/finuks/easy-rsa

Finally, initialize the PKI inside the easy-rsa directory:

cd ~/easy-rsa
./easyrsa init-pki

After completing this section you have a directory that contains all the files that are needed to create a Certificate Authority

Creating a Certificate Authority

Before you can create your CA’s private key and certificate, you need to create and populate a file called vars with some default values.

cd ~/easy-rsa
vim vars 

edit each value to reflect your own organization info. The important part here is to ensure that you do not leave any of the values blank:

set_var EASYRSA_REQ_COUNTRY    "CN"
set_var EASYRSA_REQ_PROVINCE   "Shanghai"
set_var EASYRSA_REQ_CITY       "Shanghai"
set_var EASYRSA_REQ_ORG        "ZhongZhi"
set_var EASYRSA_REQ_EMAIL      "sysfinuks@gmail.com"
set_var EASYRSA_REQ_OU         "Individual"
set_var EASYRSA_ALGO           "ec"
set_var EASYRSA_DIGEST         "sha512"

To create the root public and private key pair for your Certificate Authority, run the ./easy-rsa command again, this time with the build-ca option:

./easyrsa build-ca

In the output, you’ll see some lines about the OpenSSL version and you will be prompted to enter a passphrase for your key pair.You will need to input the passphrase any time that you need to interact with your CA, for example to sign or revoke a certificate.

You will also be asked to confirm the Common Name (CN) for your CA. The CN is the name used to refer to this machine in the context of the Certificate Authority. You can enter any string of characters for the CA’s Common Name but for simplicity’s sake, press ENTER to accept the default name

Note: If you don’t want to be prompted for a password every time you interact with your CA, you can run the build-ca command with the nopass option, like this:

./easyrsa build-ca nopass

You now have two important files ~/easy-rsa/pki/ca.crt and ~/easy-rsa/pki/private/ca.key which make up the public and private components of a Certificate Authority.

  • ca.crt: is the CA’s public certificate file. Users, servers, and clients will use this certificate to verify that they are part of the same web of trust. Every user and server that uses your CA will need to have a copy of this file. All parties will rely on the public certificate to ensure that someone is not impersonating a system and performing a Man-in-the-middle attack.
  • ca.key: is the private key that the CA uses to sign certificates for servers and clients. If an attacker gains access to your CA and, in turn, your ca.key file, you will need to destroy your CA. This is why your ca.key file should only be on your CA machine and that, ideally, your CA machine should be kept offline when not signing certificate requests as an extra security measure.

OpenVPN Server Setup

Installing OpenVPN and Easy-RSA

choose your another user, you will need to create a new directory on the OpenVPN Server as your non-root user called ~/easy-rsa:

mkdir ~/easy-rsa

Now you will need to create a symlink from the easyrsa script that the package installed into the ~/easy-rsa directory that you just created:

ln -s /usr/share/easy-rsa/* ~/easy-rsa/

Finally, ensure the directory’s owner is your non-root sudo user and restrict access to that user using chmod:

sudo chown finuks ~/easy-rsa
chmod 700 ~/easy-rsa

Once these programs are installed and have been moved to the right locations on your system, the next step is to create a Public Key Infrastructure (PKI) on the OpenVPN server so that you can request and manage TLS certificates for clients and other servers that will connect to your VPN.

Creating a PKI for OpenVPN

Before you can create your OpenVPN server’s private key and certificate, you need to create a local Public Key Infrastructure directory on your OpenVPN server. You will use this directory to manage the server and clients’ certificate requests instead of making them directly on your CA server.

cd ~/easy-rsa
vim vars

Once the file is opened, paste in the following two lines:

set_var EASYRSA_ALGO "ec"
set_var EASYRSA_DIGEST "sha512"

These are the only two lines that you need in this vars file on your OpenVPN server since it will not be used as a Certificate Authority. They will ensure that your private keys and certificate requests are configured to use modern Elliptic Curve Cryptography (ECC) to generate keys and secure signatures for your clients and OpenVPN server.

Configuring your OpenVPN & CA servers to use ECC means when a client and server attempt to establish a shared symmetric key, they can use Elliptic Curve algorithms to do their exchange. Using ECC for a key exchange is significantly faster than using plain Diffie-Hellman with the classic RSA algorithm since the numbers are much smaller and the computations are faster.

Background: When clients connect to OpenVPN, they use asymmetric encryption (also known as public/private key) to perform a TLS handshake.However, when transmitting encrypted VPN traffic, the server and clients use symmetric encryption, which is also known as shared key encryption.

There is much less computational overhead with symmetric encryption compared to asymmetric: the numbers that are used are much smaller, and modern CPUs integrate instructions to perform optimized symmetric encryption operations.To make the switch from asymmetric to symmetric encryption, the OpenVPN server and client will use the Elliptic Curve Diffie-Hellman (ECDH) algorithm to agree on a shared secret key as quickly as possible.

Once you have populated the vars file you can proceed with creating the PKI directory. To do so, run the easyrsa script with the init-pki option. Although you already ran this command on the CA server as part of the prerequisites, it’s necessary to run it here because your OpenVPN server and CA server have separate PKI directories:

./easyrsa init-pki

Note that on your OpenVPN server there is no need to create a Certificate Authority. Your CA server is solely responsible for validating and signing certificates. The PKI on your VPN server is only used as a convenient and centralized place to store certificate requests and public certificates.

Creating an OpenVPN Server Certificate Request and Private Key

Now that your OpenVPN server has all the prerequisites installed, the next step is to generate a private key and Certificate Signing Request (CSR) on your OpenVPN server. After that you’ll transfer the request over to your CA to be signed, creating the required certificate. Once you have a signed certificate, you’ll transfer it back to the OpenVPN server and install it for the server to use.

To start, navigate to the ~/easy-rsa directory on your OpenVPN Server as your non-root user:

cd ~/easy-rsa

Now you’ll call the easyrsa with the gen-req option followed by a Common Name (CN) for the machine. The CN can be anything you like but it can be helpful to make it something descriptive. Throughout this tutorial, the OpenVPN Server’s CN will be openvpn-server. Be sure to include the nopass option as well. Failing to do so will password-protect the request file which could lead to permissions issues later on.

./easyrsa gen-req openvpn-server nopass

This will create a private key for the server and a certificate request file called server.req. Copy the server key to the /etc/openvpn/server directory:

sudo cp /home/finuks/easy-rsa/pki/private/openvpn-server.key /etc/openvpn/server/

After completing these steps, you have successfully created a private key for your OpenVPN server. You have also generated a Certificate Signing Request for the OpenVPN server. The CSR is now ready for signing by your CA.

Signing the OpenVPN Server’s Certificate Request

Now the CA server needs to know about the server certificate and validate it. Once the CA validates and relays the certificate back to the OpenVPN server, clients that trust your CA will be able to trust the OpenVPN server as well.

On the OpenVPN server, as your non-root user, use SCP or another transfer method to copy the server.req certificate request to the CA server for signing:

sudo cp -f ~/easy-rsa/pki/reqs/openvpn-server.req /tmp
chmod 777 /tmp/openvpn-server.req

the next step is to log in to the CA server as the non-root user that you created to manage your CA. You’ll cd to the ~/easy-rsa directory where you created your PK and then import the certificate request using the easyrsa script:

cd ~/easy-rsa
./easyrsa import-req /tmp/openvpn-server.req openvpn-server

Next, sign the request by running the easyrsa script with the sign-req option, followed by the request type and the Common Name. The request type can either be client or server. Since we’re working with the OpenVPN server’s certificate request, be sure to use the server request type:

# 第一个参数是类型,第二个是导入的请求名
./easyrsa sign-req server openvpn-server

Note that if you encrypted your CA private key, you’ll be prompted for your password at this point.

With those steps complete, you have signed the OpenVPN server’s certificate request using the CA server’s private key. The resulting “openvpn-server.crt” file contains the OpenVPN server’s public encryption key, as well as a signature from the CA server. The point of the signature is to tell anyone who trusts the CA server that they can also trust the OpenVPN server when they connect to it.

To finish configuring the certificates, copy the openvpn-server.crt and ca.crt files from the CA server to the OpenVPN server:

cp -f ./pki/issued/openvpn-server.crt ./pki/ca.crt /tmp/
chmod 777 /tmp/*.crt

Now back on your OpenVPN server, copy the files from /tmp to /etc/openvpn/server:

sudo cp -f /tmp/{openvpn-server.crt,ca.crt} /etc/openvpn/server/

Now OpenVPN server is nearly ready to accept connections.

Configuring OpenVPN Cryptographic Material

For an additional layer of security, we’ll add an extra shared secret key that the server and all clients will use with OpenVPN’s tls-crypt directive.This option is used to obfuscate the TLS certificate that is used when a server and client connect to each other initially. It is also used by the OpenVPN server to perform quick checks on incoming packets: if a packet is signed using the pre-shared key, then the server processes it; if it is not signed, then the server knows it is from an untrusted source and can discard it without having to perform additional decryption work.

This option will help ensure that your OpenVPN server is able to cope with unauthenticated traffic, port scans, and Denial of Service attacks, which can tie up server resources. It also makes it harder to identify OpenVPN network traffic.

To generate the tls-crypt pre-shared key, run the following on the OpenVPN server in the ~/easy-rsa directory:

cd ~/easy-rsa
openvpn --genkey --secret ta.key

The result will be a file called ta.key. Copy it to the /etc/openvpn/server/ directory:

sudo cp ./ta.key /etc/openvpn/server/

With these files in place on the OpenVPN server you are ready to create client certificates and key files for your users, which you will use to connect to the VPN.

Configuring OpenVPN Server

OpenVPN has numerous configuration options available to customize your server for your specific needs. In this section, we will provide instructions on how to set up an OpenVPN server configuration based on one of the sample configuration files that is included within this software’s documentation.

First, copy the sample server.conf file as a starting point for your own configuration file:

cp -f /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /etc/openvpn/server/
gunzip /etc/openvpn/server/server.conf.gz

Open the new file for editing with the text editor of your choice.

sudo vim /etc/openvpn/server/server.conf
# Which TCP/UDP port should OpenVPN listen on?
# If you want to run multiple OpenVPN instances
# on the same machine, use a different port
# number for each one.  You will need to
# open up this port on your firewall.
port 1194

# TCP or UDP server?
;proto tcp
proto udp

If you do switch the protocol to TCP, you will need to change the explicit-exit-notify directive’s value from 1 to 0,as this directive is only used by UDP. Failing to do so while using TCP will cause errors when you start the OpenVPN service.Find the explicit-exit-notify line at the end of the file and change the value to 0:

;explicit-exit-notify 1
explicit-exit-notify 0

Point to Non-Default Credentials

If you selected a different name during the ./easyrsa gen-req server command earlier, modify the cert and key lines in the server.conf configuration file so that they point to the appropriate .crt and .key files. If you used the default name, server, this is already set correctly:

ca ca.crt
;cert server.crt
;key server.key  # This file should be kept secret
cert openvpn-server.crt
key openvpn-server.key

find the line containing a dh directive, which defines Diffie-Hellman parameters. Since we’ve configured all the certificates to use Elliptic Curve Cryptography, there is no need for a Diffie-Hellman seed file. Comment out the existing line that looks like dh dh2048.pem or dh dh.pem. The filename for the Diffie-Hellman key may be different than what is listed in the example server configuration file. Then add a line after it with the contents dh none:

# Diffie hellman parameters.
# Generate your own with:
#   openssl dhparam -out dh2048.pem 2048
;dh dh2048.pem
dh none

set subnet IP

# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
server 10.8.0.0 255.255.255.0

Below lines will tell your client to use the free OpenDNS resolvers at the listed IP addresses. If you prefer other DNS resolvers you can substitute them in place of the highlighted IPs.This will assist clients in reconfiguring their DNS settings to use the VPN tunnel as the default gateway.

# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses.  CAVEAT:
# http://openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
;push "dhcp-option DNS 208.67.222.222"
;push "dhcp-option DNS 208.67.220.220"
push "dhcp-option DNS 223.5.5.5"

Allow clinets “see” each other

# Uncomment this directive to allow different
# clients to be able to "see" each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server's TUN/TAP interface.
client-to-client

We’ll need to change a few lines in this file. First, find the HMAC section of the configuration by searching for the tls-auth directive. This line will be enabled by default. Comment it out by adding a ; to the beginning of the line. Then add a new line after it containing the value tls-crypt ta.key only:

# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
#   openvpn --genkey --secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
;tls-auth ta.key 0 # This file is secret
tls-crypt ta.key

find the section on cryptographic ciphers by looking for the cipher lines. The default value is set to AES-256-CBC, however, the AES-256-GCM cipher offers a better level of encryption, performance, and is well supported in up-to-date OpenVPN clients. We’ll comment out the default value by adding a ; sign to the beginning of this line, and then we’ll add another line after it containing the updated value of AES-256-GCM:

;cipher AES-256-CBC
cipher AES-256-GCM

Right after this line, add an auth directive to select the HMAC message digest algorithm. For this, SHA256 is a good choice:

auth SHA256

we want OpenVPN to run with no privileges once it has started, so we need to tell it to run with a user nobody and group nogroup. To enable this, find and uncomment the user nobody and group nogroup lines by removing the ; sign from the beginning of each line:

user nobody
group nogroup

You have now finished configuring your OpenVPN general settings.

Adjusting the OpenVPN Server Networking Configuration

There are some aspects of the server’s networking configuration that need to be tweaked so that OpenVPN can correctly route traffic through the VPN. The first of these is IP forwarding, a method for determining where IP traffic should be routed. This is essential to the VPN functionality that your server will provide.To adjust your OpenVPN server’s default IP forwarding setting, open the /etc/sysctl.conf file using nano or your preferred editor:

sudo vim /etc/sysctl.conf

Then uncomment the following line at the bottom of the file

#net.ipv4.ip_forward=1
net.ipv4.ip_forward=1

To read the file and load the new values for the current session, type:

sudo sysctl -p

Now your OpenVPN server will be able to forward incoming traffic from one ethernet device to another. This setting makes sure the server can direct traffic from clients that connect on the virtual VPN interface out over its other physical ethernet devices. This configuration will route all web traffic from your client via your server’s IP address, and your client’s public IP address will effectively be hidden.

Firewall Configuration

So far, you’ve installed OpenVPN on your server, configured it, and generated the keys and certificates needed for your client to access the VPN. However, you have not yet provided OpenVPN with any instructions on where to send incoming web traffic from clients. You can stipulate how the server should handle client traffic by establishing some firewall rules and routing configurations.

Assuming you followed the prerequisites at the start of this tutorial, you should already have ufw installed and running on your server. To allow OpenVPN through the firewall, you’ll need to enable masquerading, an iptables concept that provides on-the-fly dynamic network address translation (NAT) to correctly route client connections.

Before opening the firewall configuration file to add the masquerading rules, you must first find the public network interface of your machine. To do this, type:

ip route list default

Your public interface is the string found within this command’s output that follows the word “dev”.When you have the interface associated with your default route, open the /etc/ufw/before.rules file to add the relevant configuration:

sudo vim /etc/ufw/before.rules

UFW rules are typically added using the ufw command. Rules listed in the before.rules file, though, are read and put into place before the conventional UFW rules are loaded. Towards the top of the file, add the highlighted lines below. This will set the default policy for the POSTROUTING chain in the nat table and masquerade any traffic coming from the VPN. Remember to replace eth0 in the -A POSTROUTING line below with the interface you found in the above command:

#
# rules.before
#
# Rules that should be run before the ufw command line added rules. Custom
# rules should be added to one of these chains:
#   ufw-before-input
#   ufw-before-output
#   ufw-before-forward
#

# START OPENVPN RULES
# NAT table rules
*nat
:POSTROUTING ACCEPT [0:0]
# Allow traffic from OpenVPN client to eth0 (change to the interface you discovered!)
-A POSTROUTING -s 10.8.0.0/8 -o eth0 -j MASQUERADE
COMMIT
# END OPENVPN RULES

# Don't delete these required lines, otherwise there will be errors
*filter
......

Next, you need to tell UFW to allow forwarded packets by default as well. To do this, open the /etc/default/ufw file:

sudo vim /etc/default/ufw

Inside, find the DEFAULT_FORWARD_POLICY directive and change the value from DROP to ACCEPT:

#DEFAULT_FORWARD_POLICY="DROP"
DEFAULT_FORWARD_POLICY="ACCEPT"

Next, adjust the firewall itself to allow traffic to OpenVPN. If you did not change the port and protocol in the /etc/openvpn/server.conf file, you will need to open up UDP traffic to port 1194. If you modified the port and/or protocol, substitute the values you selected here.In case you forgot to add the SSH port when following the prerequisite tutorial, add it here as well:

sudo ufw allow 1194/udp
sudo ufw allow OpenSSH

Note: If you are using a different firewall or have customized your UFW configuration, you may need to add additional firewall rules. For example, if you decide to tunnel all of your network traffic over the VPN connection, you will need to ensure that port 53 traffic is allowed for DNS requests, and ports like 80 and 443 for HTTP and HTTPS traffic respectively. If there are other protocols that you are using over the VPN then you will need to add rules for them as well.

After adding those rules, disable and re-enable UFW to restart it and load the changes from all of the files you’ve modified:

sudo ufw reload

Your server is now configured to correctly handle OpenVPN traffic.

Starting OpenVPN

OpenVPN runs as a systemd service, so we can use systemctl to manage it. We will configure OpenVPN to start up at boot so you can connect to your VPN at any time as long as your server is running. To do this, enable the OpenVPN service by adding it to systemctl:

sudo systemctl -f enable openvpn-server@server.service
sudo systemctl start openvpn-server@server.service
sudo systemctl status openvpn-server@server.service

We’ve now completed the server-side configuration for OpenVPN.

OpenVPN Client Setup

Creating the Client Configuration Infrastructure

Creating configuration files for OpenVPN clients can be somewhat involved, as every client must have its own config and each must align with the settings outlined in the server’s configuration file. Rather than writing a single configuration file that can only be used on one client, this step outlines a process for building a client configuration infrastructure which you can use to generate config files on-the-fly. You will first create a “base” configuration file then build a script which will allow you to generate unique client config files, certificates, and keys as needed.

Get started by creating a new directory where you will store client configuration files within the client-configs directory you created earlier:

mkdir -p ~/client-configs/files

Next, copy an example client configuration file into the client-configs directory to use as your base configuration:

cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf ~/client-configs/base.conf

Open ~/client-configs/base.conf using your preferred text editor:

Inside, locate the remote directive. This points the client to your OpenVPN server address – the public IP address of your OpenVPN server. If you decided to change the port that the OpenVPN server is listening on, you will also need to change 1194 to the port you selected:

vim ~/client-configs/base.conf
# The hostname/IP and port of the server.
# You can have multiple remote entries
# to load balance between the servers.
;remote my-server-1 1194
;remote my-server-2 1194
remote x.x.x.x 1194

Be sure that the protocol matches the value you are using in the server configuration:

proto udp

Next, uncomment the user and group directives by removing the ; sign at the beginning of each line:

# Downgrade privileges after initialization (non-Windows only)
user nobody
group nogroup

Find the directives that set the ca, cert, and key. Comment out these directives since you will add the certs and keys within the file itself shortly:

# SSL/TLS parms.
# See the server config file for more
# description.  It's best to use
# a separate .crt/.key file pair
# for each client.  A single ca
# file can be used for all clients.
;ca ca.crt
;cert client.crt
;key client.key

Similarly, comment out the tls-auth directive, as you will add ta.key directly into the client configuration file (and the server is set up to use tls-crypt):

# If a tls-auth key is used on the server
# then every client must also have the key.
;tls-auth ta.key 1

Mirror the cipher and auth settings that you set in the /etc/openvpn/server/server.conf file:

# Select a cryptographic cipher.
# If the cipher option is used on the server
# then you must also specify it here.
# Note that v2.4 client/server will automatically
# negotiate AES-256-GCM in TLS mode.
# See also the ncp-cipher option in the manpage
;cipher AES-256-CBC
cipher AES-256-GCM
auth SHA256

Next, add the key-direction directive somewhere in the file. You must set this to “1” for the VPN to function correctly on the client machine:

# custom
key-direction 1

Generating Client OVPN files

we’ll create a script that will compile your base configuration with the relevant certificate, key, and encryption files and then place the generated configuration in the ~/client-configs/files directory. Open a new file called make_config.sh within the ~/client-configs directory:

when you want generate a new ovpn file, just run:

cd /home/finuks/client-configs
sudo bash ./make_config.sh

make_config.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/bin/bash

# check if the target directory exist
function check_directory() {
    local directory_path="$1"
    if [ ! -d "$directory_path" ]; then
        echo "Directory '$directory_path' does not exist."
        exit 1
    fi
}

# check if the target file exist
function check_file() {
    local file_path="$1"
    if [ ! -f "$file_path" ]; then
        echo "File '$file_path' does not exist."
        exit 1
    fi
}

function gen_client_req {
    name=$1
    dir=$2

    check_directory $dir/easy-rsa
    cd $dir/easy-rsa
    ./easyrsa gen-req $name nopass
    cp -f $dir/easy-rsa/pki/private/$name.key $dir/client-configs/keys/
    cp -f $dir/easy-rsa/pki/reqs/$name.req /tmp/
    chmod 777 /tmp/$name.req
}

function import_client_req {
    name=$1
    dir=$2

    cd $dir/easy-rsa
    ./easyrsa import-req /tmp/$name.req $name
    ./easyrsa sign-req client $name
    cp -f $dir/easy-rsa/pki/issued/$name.crt /tmp/
    chmod 777 /tmp/$name.crt
}

function main {
    # get certificate name
    certificate_name=""
    while [[ -z $certificate_name ]]; do
        read -p "Enter the name of the certificate (e.g., 'openvpn-client-linux'): " certificate_name
    done

    # get openvpn user dir
    DEFAULT_OPENVPN_USER="/home/finuks"
    read -p "Enter the OpenVPN user dir,default '$DEFAULT_OPENVPN_USER'): " openvpn_user_dir
    openvpn_user_dir=${openvpn_user_dir:-$DEFAULT_OPENVPN_USER}
    check_directory $openvpn_user_dir

    # get certificate-server user dir
    DEFAULT_CA_USER="/home/ca"
    read -p "Enter the CA server user dir,default '$DEFAULT_CA_USER'): " ca_user_dir
    ca_user_dir=${ca_user_dir:-$DEFAULT_CA_USER}
    check_directory $ca_user_dir

    # run the easyrsa script with the gen-req and nopass options, along with the common name for the client:
    gen_client_req $certificate_name $openvpn_user_dir

    # import the certificate request
    import_client_req $certificate_name $ca_user_dir

    echo "copy the client certificate to the ~/client-configs/keys/ directory............."
    cp -f /tmp/$certificate_name.crt $openvpn_user_dir/client-configs/keys/
    chmod -R 777 $openvpn_user_dir/client-configs/keys/*
    echo "done"

    echo "check the ca.crt and ta.key files in the ~/client-configs/keys/ directory............"
    check_file $openvpn_user_dir/client-configs/keys/ta.key
    check_file $openvpn_user_dir/client-configs/keys/ca.crt
    echo "done"

    echo "make client ovpn config file..............."
    cd $openvpn_user_dir/client-configs
    check_file $openvpn_user_dir/client-configs/make_config.py
    python3 ./make_config.py $certificate_name $openvpn_user_dir
    chmod +x 777 $openvpn_user_dir/client-configs/files/$certificate_name.ovpn
    echo "done"
}

# Call the main function
main

make_config.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import os
import sys

# First argument: Client identifier
client_identifier = sys.argv[1]
path_prefix = sys.argv[2]

key_dir = os.path.join(path_prefix, 'client-configs/keys')
output_dir = os.path.join(path_prefix, 'client-configs/files')
base_config = os.path.join(path_prefix, 'client-configs/base.conf')

with open(base_config, 'r') as base_file, \
        open(os.path.join(output_dir, f'{client_identifier}.ovpn'), 'w') as output_file:
    output_file.write(base_file.read())
    output_file.write('\n')

    with open(os.path.join(key_dir, 'ca.crt'), 'r') as ca_file:
        output_file.write('<ca>\n')
        output_file.write(ca_file.read())
        output_file.write('</ca>\n')

    with open(os.path.join(key_dir, f'{client_identifier}.crt'), 'r') as client_crt_file:
        output_file.write('<cert>\n')
        output_file.write(client_crt_file.read())
        output_file.write('</cert>\n')

    with open(os.path.join(key_dir, f'{client_identifier}.key'), 'r') as client_key_file:
        output_file.write('<key>\n')
        output_file.write(client_key_file.read())
        output_file.write('</key>\n')

    with open(os.path.join(key_dir, 'ta.key'), 'r') as ta_key_file:
        output_file.write('<tls-crypt>\n')
        output_file.write(ta_key_file.read())
        output_file.write('</tls-crypt>\n')

Build OpenVPN from source (for debian)

Install checkinstall: Start by installing checkinstall, which is a utility used to create Debian packages from compiled software. Run the following command to install it:

sudo apt-get install checkinstall

Compile OpenVPN: Follow the steps I provided earlier to compile OpenVPN from source. Make sure you have all the necessary dependencies installed before proceeding.

./configure
make

Use checkinstall to create a Debian package: Instead of running sudo make install, use checkinstall to create a Debian package and install it. Run the following command:

sudo checkinstall

checkinstall will guide you through the process of creating the package. It will ask you for some information, such as the package name, version, maintainer, and description. You can customize these values based on your preferences.

Once the process is complete, checkinstall will generate a .deb package that you can use to install OpenVPN on your system.

Install the generated Debian package: After the package is created, you can install it using the following command:

sudo dpkg -i openvpn-<version>.deb

Replace with the actual version number of the OpenVPN package you compiled.

run the ovpn file in command

sudo cp -f k8s-worker.ovpn /etc/openvpn/client.ovpn
sudo openvpn --config /etc/openvpn/client.ovpn

Linux Server Connect to OpenVPN Server

  1. Upload the .ovpn file. Transfer the .ovpn file to your Ubuntu server.
  2. Install OpenVPN
sudo apt install openvpn
  1. Move the .ovpn file to the OpenVPN client configuration directory
sudo mv yourfile.ovpn /etc/openvpn/client/yourfile.conf
  1. Start the OpenVPN service
sudo systemctl start openvpn-client@yourfile
  1. Check the status with sudo systemctl status openvpn-client@yourfile
  2. Enable automatic startup with sudo systemctl enable openvpn-client@yourfile
  3. Besure firewall allow the protocol and port , in my case , it’s default 1194/udp port.