Skip to content

Instantly share code, notes, and snippets.

@cmd-johnson
Last active July 13, 2016 10:19
Show Gist options
  • Save cmd-johnson/772e21403167570bb9ec3f438e19c00b to your computer and use it in GitHub Desktop.
Save cmd-johnson/772e21403167570bb9ec3f438e19c00b to your computer and use it in GitHub Desktop.
Creates client certificates to be used with an OpenVPN server and outputs ovpn file contents for the new client
#!/usr/bin/env bash
# Creates OpenVPN client certificates and outputs ovpn file contents
# Typical usage would be to redirect stdout to a *.ovpn file:
# ./create-ovpn-client-certs client1 > ServerName.ovpn
# Edit these paths to match your openvpn/easy-rsa configuration
EASY_RSA_PATH=/etc/openvpn/easy-rsa
KEY_DIR=$EASY_RSA_PATH/keys
CA_CERT_PATH=/etc/openvpn/ca.crt
# Edit to match your server domain or IP and port (1194 is default)
SERVER_NAME=w.x.y.z
SERVER_PORT=1194
createClientOvpnFile() {
CLIENT_NAME=$1
# check if there already exists a certificate for the client
if [ ! -f "$EASY_RSA_PATH/keys/$CLIENT_NAME.crt" ]; then
createClientCertificate $CLIENT_NAME
error=$?
if [ $error -ne 0 ]; then
(>&2 echo "Error creating client certificate")
exit $error
fi
fi
writeFileTemplate $CLIENT_NAME
}
createClientCertificate() {
CERT_NAME=$1
cd $EASY_RSA_PATH
(>/dev/null . ./vars)
(>&2 ./build-key $CERT_NAME)
return $?
}
writeFileTemplate() {
CERT_NAME=$1
CA_CERT=$(<$CA_CERT_PATH)
CLIENT_CERT=$(<$KEY_DIR/$CERT_NAME.crt)
CLIENT_KEY=$(<$KEY_DIR/$CERT_NAME.key)
# edit template to match your client.conf configuration
cat <<- EOF
client
dev tun
proto udp
remote $SERVER_NAME $SERVER_PORT
resolv-retry infinite
nobind
user nobody
group nogroup
persist-key
persist-tun
ns-cert-type server
comp-lzo
verb 3
<ca>
$CA_CERT
</ca>
<cert>
$CLIENT_CERT
</cert>
<key>
$CLIENT_KEY
</key>
EOF
}
CLIENT_NAME=$1
if [ -z "$CLIENT_NAME" ]; then
echo "Usage: $0 client_name"
exit 1
fi
createClientOvpnFile $CLIENT_NAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment