Skip to content

Instantly share code, notes, and snippets.

@SaidTorres3
Last active January 19, 2023 03:44
Show Gist options
  • Save SaidTorres3/53c302b769ec5e89add5ddc9a6ecd8d1 to your computer and use it in GitHub Desktop.
Save SaidTorres3/53c302b769ec5e89add5ddc9a6ecd8d1 to your computer and use it in GitHub Desktop.
Create OpenVPN Server Bash Script
#!/bin/bash
# Install OpenVPN and Easy-RSA
sudo apt-get update
sudo apt-get install openvpn easy-rsa -y
# Create the OpenVPN directory structure
sudo mkdir /etc/openvpn/easy-rsa/
sudo cp -r /usr/share/easy-rsa/* /etc/openvpn/easy-rsa/
# Create the certificate authority
cd /etc/openvpn/easy-rsa/
sudo ./easyrsa init-pki
sudo ./easyrsa build-ca nopass
# Create the server certificate
sudo ./easyrsa build-server-full server nopass
# Create the client certificate
sudo ./easyrsa build-client-full client1 nopass
# Create the Diffie-Hellman parameters
sudo ./easyrsa gen-dh
# Create the OpenVPN configuration file
sudo bash -c 'cat > /etc/openvpn/server.conf << EOL
port 1194
proto udp
dev tun
ca /etc/openvpn/easy-rsa/pki/ca.crt
cert /etc/openvpn/easy-rsa/pki/issued/server.crt
key /etc/openvpn/easy-rsa/pki/private/server.key
dh /etc/openvpn/easy-rsa/pki/dh.pem
server 10.8.0.0 255.255.255.0
push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 8.8.8.8"
push "dhcp-option DNS 8.8.4.4"
keepalive 10 120
comp-lzo
user nobody
group nogroup
persist-key
persist-tun
status /var/log/openvpn-status.log
verb 3
EOL'
# Create the client .ovpn file
sudo bash -c 'cat > /etc/openvpn/client1.ovpn << EOL
client
dev tun
proto udp
remote YOUR_SERVER_IP 1194
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
auth-nocache
comp-lzo
verb 3
<ca>
$(cat /etc/openvpn/easy-rsa/pki/ca.crt)
</ca>
<cert>
$(cat /etc/openvpn/easy-rsa/pki/issued/client1.crt)
</cert>
<key>
$(cat /etc/openvpn/easy-rsa/pki/private/client1.key)
</key>
EOL'
# Enable IP forwarding and start the OpenVPN server
sudo bash -c 'echo 1 > /proc/sys/net/ipv4/ip_forward'
sudo systemctl start openvpn@server
#!/bin/bash
echo "Updating firewall rules for OpenVPN..."
# Add OpenVPN rules to firewall
sudo echo "# OpenVPN
-A ufw-before-input -p udp --dport 1194 -j ACCEPT
-A ufw-before-output -p udp --sport 1194 -j ACCEPT" >> /etc/ufw/before.rules
# Reload firewall rules
sudo ufw reload
# Enable IP masquerading
sudo iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
# Save iptables
sudo iptables-save
echo "Firewall rules updated successfully!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment