Public
Snippet $40 authored by Owo Sugiana

Script Pembuat Sertifikat OpenVPN Client

Edited
build-client-cert.sh
## https://community.openvpn.net/openvpn/wiki/EasyRSA3-OpenVPN-Howto

cd /etc/openvpn/server

if [ -z "$1" ]; then
    echo "Caranya: $0 <nama-client>"
    echo "Contoh: $0 sugiana"
    exit 0
fi

HOSTNAME=$1

if [ ! -d easyrsa3-ca ]; then
    echo "Jalankan dulu build-server-cert.sh"
    exit 0
fi

# Create config file
if [ ! -f client.ovpn ]; then
    if [ -z "$2" ]; then
        echo "File client.ovpn belum ada, tolong sertakan IP publik mesin ini."
        echo "Contoh: $0 $1 202.43.164.162"
        exit 0
    fi
    IP_PUBLIC="$2"
    cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf client.ovpn
    sed '/^proto udp/s/^/;/' client.ovpn > client.ovpn.tmp 
    sed -e 's/^;proto tcp/proto tcp/g' client.ovpn.tmp > client.ovpn 
    sed -e 's/^remote my-server-1/remote '$IP_PUBLIC'/g' client.ovpn > client.ovpn.tmp
    sed '/^ns-cert-type server/s/^/;/' client.ovpn.tmp > client.ovpn
    sed '/^tls-auth ta.key 1/s/^/;/' client.ovpn > client.ovpn.tmp
    mv client.ovpn.tmp client.ovpn
fi

if [ ! -d easyrsa3-client ]; then
    cp -r easy-rsa/easyrsa3 easyrsa3-client
fi

cd easyrsa3-client
if [ ! -d pki ]; then
    ./easyrsa init-pki || exit 1
fi
./easyrsa gen-req $HOSTNAME nopass || exit 1
cd ..

cd easyrsa3-ca
./easyrsa import-req ../easyrsa3-client/pki/reqs/$HOSTNAME.req $HOSTNAME
./easyrsa sign client $HOSTNAME
cd ..

# Backup

TMP_DIR=$HOSTNAME-tmp
CLIENT_DIR=/etc/openvpn/client
mkdir -p $TMP_DIR $CLIENT_DIR
CLIENT_DIR_FULLPATH=`realpath $CLIENT_DIR`
BACKUP_FILE=$CLIENT_DIR_FULLPATH/$HOSTNAME.tgz

cp easyrsa3-client/pki/private/$HOSTNAME.key $TMP_DIR/client.key
cp easyrsa3-ca/pki/issued/$HOSTNAME.crt $TMP_DIR/client.crt
cp easyrsa3-ca/pki/ca.crt $TMP_DIR/
cp client.ovpn $TMP_DIR/
read -p "Apakah server ini sebagai proxy (y/t, default tidak) ? " jwb 
if [ "$jwb" = "y" ]; then
    echo "route remote_host 255.255.255.255 net_gateway" >> $TMP_DIR/client.ovpn
    echo "route 0.0.0.0 0.0.0.0 vpn_gateway" >> $TMP_DIR/client.ovpn
    echo "redirect-gateway def1" >> $TMP_DIR/client.ovpn
fi
read -p "Apakah server ini mewajibkan username & password (y/t, default tidak) ? " jwb 
if [ "$jwb" = "y" ]; then
    echo "auth-user-pass" >> $TMP_DIR/client.ovpn
fi
cd $TMP_DIR
tar cfvz $BACKUP_FILE client.key client.crt ca.crt client.ovpn
cd ..
rm $TMP_DIR/client.key $TMP_DIR/client.crt $TMP_DIR/ca.crt $TMP_DIR/client.ovpn
rmdir $TMP_DIR
ls -l $BACKUP_FILE