Bash Script for Quick OpenVPN Server Setup on Ubuntu 22.04 LTS
Here's a bash script that automates the installation and configuration of OpenVPN on Ubuntu 22.04, as well as creates a client configuration file that can be used to connect to the server:
Save the below script to a file (e.g. openvpn-install.sh
), make it executable with chmod +x openvpn-install.sh
, and then run it with sudo ./openvpn-install.sh
.
This script will:
- Update and upgrade packages
- Install OpenVPN and easy-rsa
- Copy the easy-rsa scripts to the OpenVPN directory
- Create the Public Key Infrastructure (PKI), including the CA, DH params, and server certificate and key
- Create the OpenVPN server configuration file
- Enable IP forwarding
- Start and enable the
The script:
#!/bin/bash
# Update and upgrade packages
apt update && apt upgrade -y
# Install necessary packages
apt install openvpn easy-rsa -y
# Copy easy-rsa scripts to OpenVPN directory
cp -r /usr/share/easy-rsa/ /etc/openvpn/
# Create the PKI, set up the CA, the DH params, and create a server certificate and key
cd /etc/openvpn/easy-rsa/
source ./vars
./clean-all
./build-ca
./build-dh
./pkitool --initca
./pkitool --server server
openvpn --genkey --secret /etc/openvpn/ta.key
# Create the server configuration file
cat <<EOF > /etc/openvpn/server.conf
dev tun
proto udp
port 1194
ca /etc/openvpn/easy-rsa/keys/ca.crt
cert /etc/openvpn/easy-rsa/keys/server.crt
key /etc/openvpn/easy-rsa/keys/server.key
dh /etc/openvpn/easy-rsa/keys/dh2048.pem
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt
push "dhcp-option DNS 8.8.8.8"
push "dhcp-option DNS 8.8.4.4"
push "redirect-gateway def1 bypass-dhcp"
keepalive 10 120
tls-auth /etc/openvpn/ta.key 0
cipher AES-256-CBC
user nobody
group nogroup
persist-key
persist-tun
status openvpn-status.log
verb 3
EOF
# Enable IP forwarding
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf
sysctl -p
# Start and enable OpenVPN service
systemctl start openvpn@server
systemctl enable openvpn@server
# Generate client certificates and keys
cd /etc/openvpn/easy-rsa/
./pkitool client
# Create client configuration file
cat <<EOF > /etc/openvpn/client.conf
client
dev tun
proto udp
remote $(hostname -I | awk '{print $1}') 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca /etc/openvpn/easy-rsa/keys/ca.crt
cert /etc/openvpn/easy-rsa/keys/client.crt
key /etc/openvpn/easy-rsa/keys/client.key
tls-auth /etc/openvpn/ta.key 1
cipher AES-256-CBC
verb 3
EOF
# Restart OpenVPN service
systemctl restart openvpn@server
echo "OpenVPN server installation and configuration complete."
echo "The client configuration file is located at /etc/openvpn/client.conf"