scripts/openvpn-client.sh

110 lines
2.5 KiB
Bash
Executable File

#!/bin/bash
# this script is to be run on server after the server script!
# tested on Oracle cloud with Ubuntu 20.04 (IPv6 was not configured there, traffic goes through IPv4)
# to connect on Linux:
# sudo openvpn --config ovpnc01.ovpn
SERVER='vpn_domain_name_goes_here.com'
PORT=443
PROTOCOL='tcp'
USR=$(logname)
RSA_DIR="/home/${USR}/easy-rsa"
CLIENT_DIR="/home/${USR}/client-configs"
KEY_DIR="${CLIENT_DIR}/keys"
FILES_DIR="${CLIENT_DIR}/files"
user=$(whoami)
if [ $user != root ]; then
echo "You are using a non-privileged account"
exit -1
fi
if ! test -d $RSA_DIR; then
echo 'Run the server script first!'
exit -1
fi
if [[ ! ${1+x} ]]; then
echo 'Provide a client name as an argument to this script!'
exit -1
else
CLIENT=$1
fi
if ! test -d $CLIENT_DIR; then
mkdir $CLIENT_DIR
mkdir $KEY_DIR
mkdir $FILES_DIR
cp /etc/openvpn/server/ta.key "${KEY_DIR}/"
cp /etc/openvpn/server/ca.crt "${KEY_DIR}/"
else
echo 'Well, hello friend!'
fi
# create a request and get a signed certificate out of it
cd $RSA_DIR
./easyrsa gen-req $CLIENT nopass
./easyrsa import-req "${RSA_DIR}/pki/reqs/${CLIENT}.req" $CLIENT
./easyrsa sign-req client $CLIENT
cp "${RSA_DIR}/pki/private/${CLIENT}.key" "${KEY_DIR}/"
cp "${RSA_DIR}/pki/issued/${CLIENT}.crt" "${KEY_DIR}/"
# create a config file for the client
cd $FILES_DIR
CFG=$(cat <<EOF
client
dev tun
proto ${PROTOCOL}
remote ${SERVER} ${PORT}
resolv-retry infinite
nobind
user nobody
group nogroup
persist-key
persist-tun
remote-cert-tls server
verb 3
mute-replay-warnings
cipher AES-256-GCM
auth SHA256
key-direction 1
# ipv6 params, basically it breaks IPv6 stuff so traffic only goes though IPv4
ifconfig-ipv6 fd00::2 fd00::1
redirect-gateway ipv6 def1
# for linux clients that do not use systemd-resolved to manage DNS
; script-security 2
; up /etc/openvpn/update-resolv-conf
; down /etc/openvpn/update-resolv-conf
# for linux clients that use systemd-resolved
; script-security 2
; up /etc/openvpn/update-systemd-resolved
; down /etc/openvpn/update-systemd-resolved
; down-pre
; dhcp-option DOMAIN-ROUTE .
# keys:
EOF
)
cat <(echo "$CFG") \
<(echo -e '<ca>') \
${KEY_DIR}/ca.crt \
<(echo -e '</ca>\n<cert>') \
${KEY_DIR}/${CLIENT}.crt \
<(echo -e '</cert>\n<key>') \
${KEY_DIR}/${CLIENT}.key \
<(echo -e '</key>\n<tls-crypt>') \
${KEY_DIR}/ta.key \
<(echo -e '</tls-crypt>') \
> ${CLIENT}.ovpn
chown -hR "${USR}:${USR}" "${CLIENT_DIR}"
chmod -R 700 $CLIENT_DIR