Skip to content

Instantly share code, notes, and snippets.

@starkers
Last active June 10, 2019 03:01
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save starkers/7209abc5bb025733bf2e to your computer and use it in GitHub Desktop.
Save starkers/7209abc5bb025733bf2e to your computer and use it in GitHub Desktop.
Generate a new client for OpenVPN, create a .ovpn file and bundle it into a zip
#!/usr/bin/env bash
# NB: I use this on centos 6 but should work on other stuff
#
# Ensure that reverse DNS works so it can lookup its IP/hostname
# Also relies on "zip" and dig
#
# ....I should probably do some more checks on:
# Destination folders existence
# client cert is correctly inserted into the index
# host lookup worked
# plenty to fix up
if [ ! "$1" ]; then
echo Specify client name ; exit
fi
CLIENT=$1
#ensure we have some packages (dig to check my IP, zip to make a bundled .zip)
if [ ! `rpm -qa | grep ^zip` ]; then
echo "Please install zip: yum install zip" ; exit
fi
if [ ! `rpm -qa | grep ^bind-utils` ]; then
echo "Please install dig: yum install bind-utils" ; exit
fi
EZRSA=/etc/openvpn/easy-rsa
if [ -f "$EZRSA/keys/$1.key" ]; then
echo Looks like $1 already has a key
ls -l $EZRSA/keys/$1.*
exit
fi
echo +Generating client cert for $1
cd $EZRSA
source vars
# Generate the key
export EASY_RSA="${EASY_RSA:-.}"
"$EASY_RSA/pkitool" --batch $1
HOST="$(curl -s https://outboundip.com | awk '{print $1}')"
DIR=~/clients
if [ ! -d "$DIR" ]; then
mkdir -p "$DIR"
fi
CONF="$DIR/$CLIENT/$CLIENT.ovpn"
if [ ! -f $EZRSA/keys/$CLIENT.crt ]; then
echo "No client .crt found : $EZRSA/keys/$CLIENT.crt" ; exit
fi
if [ ! -f $EZRSA/keys/$CLIENT.key ]; then
echo "No client .key found : $EZRSA/keys/$CLIENT.key" ; exit
fi
rm -rf "$DIR/$CLIENT"
mkdir -p "$DIR/$CLIENT"
cat > "$CONF" <<EOF
client
dev tun
proto udp
remote $HOST 1194
#ping every 5 seconds, reconnect if no ping for 30 sec:
keepalive 5 30
resolv-retry infinite
nobind
persist-key
persist-tun
comp-lzo
verb 3
EOF
printf "<ca>\n" >> "$CONF"
cat $EZRSA/keys/ca.crt >> "$CONF"
cp $EZRSA/keys/ca.crt "$DIR/$CLIENT"/.
printf "</ca>\n" >> "$CONF"
printf "<cert>\n" >> "$CONF"
cat $EZRSA/keys/$CLIENT.crt >> "$CONF"
cp $EZRSA/keys/$CLIENT.crt "$DIR/$CLIENT"/.
printf "</cert>\n" >> "$CONF"
printf "<key>\n" >> "$CONF"
cat $EZRSA/keys/$CLIENT.key >> "$CONF"
cp $EZRSA/keys/$CLIENT.key "$DIR/$CLIENT"/.
printf "</key>\n" >> "$CONF"
cd $DIR
ZIP="$CLIENT-`date +%y%m%d`.zip"
zip -rq "$ZIP" "$CLIENT/" && echo "New account and config+cert bundle created.. see: $DIR/$ZIP"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment