openvpn/create_key_config.sh

797 lines
19 KiB
Bash
Executable File

#!/usr/bin/env bash
# ==========
# Script creates konfiguration for a given key name
# ==========
script_dir="$(dirname $(realpath $0))"
log_file="$(mktemp)"
_date="$(date +%Y-%m-%d-%H%M)"
key_names_reserverd="ta ca server"
#---------------------------------------
#-----------------------------
# Some functions
#-----------------------------
#---------------------------------------
clean_up() {
# Perform program exit housekeeping
rm $log_file
exit $1
}
trim() {
local var="$*"
var="${var#"${var%%[![:space:]]*}"}" # remove leading whitespace characters
var="${var%"${var##*[![:space:]]}"}" # remove trailing whitespace characters
echo -n "$var"
}
is_number() {
return $(test ! -z "${1##*[!0-9]*}" > /dev/null 2>&1);
# - also possible
# -
#[[ ! -z "${1##*[!0-9]*}" ]] && return 0 || return 1
#return $([[ ! -z "${1##*[!0-9]*}" ]])
}
is_int() {
return $(test "$@" -eq "$@" > /dev/null 2>&1);
}
echononl(){
echo X\\c > /tmp/shprompt$$
if [ `wc -c /tmp/shprompt$$ | awk '{print $1}'` -eq 1 ]; then
echo -e -n "$*\\c" 1>&2
else
echo -e -n "$*" 1>&2
fi
rm /tmp/shprompt$$
}
error(){
echo ""
echo -e "\t[ \033[31m\033[1mError\033[m ]: $*"
echo ""
}
fatal(){
echo ""
echo -e "\t[ \033[31m\033[1mFatal\033[m ]: $*"
echo ""
echo -e "\t\033[37m\033[1mInstalllation will be interrupted\033[m\033[m"
echo ""
clean_up 1
}
warn (){
echo ""
echo -e "\t[ \033[33m\033[1mWarning\033[m ]: $*"
echo ""
}
info (){
echo ""
echo -e "\t[ \033[32m\033[1mInfo\033[m ]: $*"
echo ""
}
echo_done() {
echo -e "\033[80G[ \033[32mdone\033[m ]"
}
echo_ok() {
echo -e "\033[80G[ \033[32mok\033[m ]"
}
echo_warning() {
echo -e "\033[80G[ \033[33m\033[1mwarn\033[m ]"
}
echo_failed(){
echo -e "\033[80G[ \033[1;31mfailed\033[m ]"
}
echo_skipped() {
echo -e "\033[80G[ \033[37mskipped\033[m ]"
}
detect_os_1 () {
if $(which lsb_release > /dev/null 2>&1) ; then
os_dist="$(lsb_release -i | awk '{print tolower($3)}')"
os_version="$(lsb_release -r | awk '{print tolower($2)}')"
os_codename="$(lsb_release -c | awk '{print tolower($2)}')"
if [[ "$os_dist" = "debian" ]]; then
if $(echo "$os_version" | grep -q '\.') ; then
os_version=$(echo "$os_version" | cut --delimiter='.' -f1)
fi
fi
elif [[ -e "/etc/os-release" ]]; then
. /etc/os-release
os_dist=$ID
os_version=${os_version_ID}
fi
# remove whitespace from os_dist and os_version
os_dist="${os_dist// /}"
os_version="${os_version// /}"
}
trap clean_up SIGHUP SIGINT SIGTERM
#---------------------------------------
#-----------------------------
# Check some prerequisites
#-----------------------------
#---------------------------------------
# - Set variable
# - os_dist
# - os_version
# - os_codename
# -
detect_os_1
clear
echo ""
echo -e "\033[21G\033[32mCreate configuration for a given OpenVPN key.. \033[m"
echo ""
echo ""
declare -a conf_file_arr=()
declare -a conf_name_arr=()
for _conf_file in `ls ${script_dir}/conf/server-*.conf 2>/dev/null` ; do
conf_file_arr+=("${_conf_file}")
_basename=$(basename $_conf_file)
_tmp_name=${_basename%%.*}
_tmp_name=${_tmp_name#*-}
conf_name_arr+=("$_tmp_name")
done
if [[ ${#conf_file_arr[@]} -lt 1 ]] ; then
fatal "NO Configuration found!"
fi
echo ""
declare -i i=0
if [[ ${#conf_file_arr[@]} -gt 1 ]] ; then
echo ""
echo "Which Configuration should be loaded?"
echo ""
for _conf_file in ${conf_file_arr[@]} ; do
echo " [${i}] ${conf_name_arr[${i}]}"
(( i++ ))
done
_OK=false
echo
echononl "Eingabe: "
while ! $_OK ; do
read _IN
if is_number "$_IN" && [[ -n ${conf_file_arr[$_IN]} ]]; then
conf_file=${conf_file_arr[$_IN]}
_OK=true
else
echo ""
echo -e "\tFalsche Eingabe !"
echo ""
echononl "Eingabe: "
fi
done
else
conf_file=${conf_file_arr[0]}
fi
echo ""
echo -e "\033[32m--\033[m"
echo ""
#---------------------------------------
#-----------------------------
# Read Configurations from $conf_file
#-----------------------------
#---------------------------------------
echononl " Load Configuration File $(basename ${conf_file}).."
if [[ ! -f "$conf_file" ]]; then
echo_failed
fatal "Configuration file \033[37m\033[1m$(basename ${conf_file})\033[m not found!"
else
source "${conf_file}" > $log_file 2>&1
if [[ $? -eq 0 ]]; then
echo_ok
else
echo_failed
fatal "$(cat $log_file)"
fi
fi
[[ "${SERVER_CIPHER,,}" = "none" ]] && SERVER_CIPHER="BF-CBC"
[[ "${SERVER_CIPHER,,}" = "" ]] && SERVER_CIPHER="BF-CBC"
if [[ -z "$LZO_COMPRESSION" ]]; then
LZO_COMPRESSION=true
elif [[ "${LZO_COMPRESSION,,}" = "yes" ]] ; then
LZO_COMPRESSION=true
elif [[ "${LZO_COMPRESSION,,}" = "no" ]] ; then
LZO_COMPRESSION=false
elif [[ "$LZO_COMPRESSION" != "true" ]] && [[ "$LZO_COMPRESSION" != "false" ]] ; then
fatal "Wrong value for variable 'LZO_COMPRESSION' (${LZO_COMPRESSION})"
elif ! $LZO_COMPRESSION ; then
LZO_COMPRESSION=false
elif $LZO_COMPRESSION ; then
LZO_COMPRESSION=true
fi
EASY_RSA_DIR="${OPENVPN_BASE_DIR}/easy-rsa"
if [[ -d "${OPENVPN_BASE_DIR}/pki" ]] ; then
EASYRSA_LAYOUT_NEW=true
else
EASYRSA_LAYOUT_NEW=false
fi
if [[ -z "$OPENVPN_KEY_DIR" ]] ; then
if $EASYRSA_LAYOUT_NEW ; then
OPENVPN_KEY_DIR="${OPENVPN_BASE_DIR}/pki"
else
OPENVPN_KEY_DIR="${OPENVPN_BASE_DIR}/keys"
fi
fi
if [[ -z "$OPENVPN_CCD_DIR" ]] ; then
if $EASYRSA_LAYOUT_NEW ; then
OPENVPN_CCD_DIR="${OPENVPN_BASE_DIR}/ccd"
else
OPENVPN_CCD_DIR="${OPENVPN_BASE_DIR}/ccd/server-${OPENVPN_NAME}"
fi
fi
_CA_CERT="${OPENVPN_KEY_DIR}/ca.crt"
_TA_KEY="${OPENVPN_KEY_DIR}/ta.key"
echo ""
echo -e "\033[32m--\033[m"
echo ""
NEW_KEY_NAME=""
if [ -z "$NEW_KEY_NAME" ]; then
echo "Insert an existing key name you wish to create the configuration."
echo ""
echo ""
echononl "key name to create configuration: "
read NEW_KEY_NAME
while [ "X$NEW_KEY_NAME" = "X" ] ; do
echo -e "\n\t\033[33m\033[1mKey name is required!\033[m\n"
echononl "key name: "
read NEW_KEY_NAME
done
fi
_CLIENT_CN="${KEY_CN}-${NEW_KEY_NAME}"
if $EASYRSA_LAYOUT_NEW ; then
_CLIENT_CERT="${OPENVPN_KEY_DIR}/issued/${_CLIENT_CN}.crt"
_CLIENT_KEY="${OPENVPN_KEY_DIR}/private/${_CLIENT_CN}.key"
else
_CLIENT_CERT="${OPENVPN_KEY_DIR}/${NEW_KEY_NAME}.crt"
_CLIENT_KEY="${OPENVPN_KEY_DIR}/${NEW_KEY_NAME}.key"
fi
if [[ ! -f "${_CLIENT_KEY}" ]]; then
fatal "Key for '$NEW_KEY_NAME' not found"
fi
for _name in $key_names_reserverd ; do
[[ "$_name" = "$NEW_KEY_NAME" ]] && fatal "Name '$NEW_KEY_NAME' cannot be used - its a reserved name!"
done
echo ""
echo -e "\033[32m--\033[m"
echo ""
echo "Enter the password for key ${NEW_KEY_NAME}.key"
echo ""
echo -e "\033[33m\033[1mLeave empty if you don't know the password.\033[m"
echo ""
echononl "Password for key $(basename "${_CLIENT_KEY}"): "
read KEY_PW
if [[ -z "$(trim $KEY_PW)" ]] ; then
KEY_PW="- Not known -"
fi
echo ""
echo -e "\033[32m--\033[m"
echo ""
echo "Give the username in whom's home directory the key material and"
echo "OpenVPn configuration shoud be stored"
echo ""
echo ""
if [[ -n "$DEFAULT_USER_TO_COPY_CREDENTIALS" ]] ; then
echo -e " Defaults to user '${DEFAULT_USER_TO_COPY_CREDENTIALS}'"
echo ""
fi
user_name=""
if [[ -n "$DEFAULT_USER_TO_COPY_CREDENTIALS" ]] ; then
echononl "Username: [${DEFAULT_USER_TO_COPY_CREDENTIALS}]: "
read user_name
if [[ "X$user_name" = "X" ]]; then
user_name="${DEFAULT_USER_TO_COPY_CREDENTIALS}"
fi
else
echononl "Username: "
read user_name
while [[ "X$user_name" = "X" ]]; do
echo -e "\n\t\033[33m\033[1mUsername is required!\033[m\n"
echononl "Username: "
read user_name
done
fi
if getent passwd "$user_name" > /dev/null 2>&1; then
_home_dir="$(eval echo "~$user_name")"
if [[ ! -d "$_home_dir" ]] ; then
fatal "User '$user_name' exists, but no home directory found!"
fi
else
fatal "User '$user_name' does not exist!"
fi
_target_dir="${_home_dir}/VPN/${_CLIENT_CN}"
clear
echo ""
echo -e "\033[32m==========\033[m"
echo "Create OpenVPN configuration and save also key material."
echo -e "\033[32m==========\033[m"
echo ""
echo "Key Name ...............: $NEW_KEY_NAME"
echo "Client Key..............: $(basename "$_CLIENT_KEY")"
echo "Client Cert.............: $(basename "$_CLIENT_CERT")"
echo "Key Password............: $KEY_PW"
echo "Common Name.............: $_CLIENT_CN"
echo ""
echo "Target directory........: $_target_dir"
info "Going to create configuration for key \033[37m\033[1m${NEW_KEY_NAME}.key\033[m.."
echo -n "To continue type uppercase 'YES': "
read OK
echo ""
if [[ "$OK" != "YES" ]] ; then
fatal "Abort by user request - Answer as not 'YES'"
fi
#---------------------------------------
#-----------------------------
# Create OpenVPN configuration and save also key material.
#-----------------------------
#---------------------------------------
echo ""
_client_conf_dir="${OPENVPN_BASE_DIR}/client-configs"
_client_conf_file="${_client_conf_dir}/${NEW_KEY_NAME}.conf"
echononl " Create client config dir '$_client_conf_dir'.."
if [[ ! -d "$_client_conf_dir" ]]; then
mkdir "$_client_conf_dir" > $log_file 2>&1
if [[ $? -eq 0 ]]; then
echo_ok
else
echo_failed
error "$(cat $log_file)"
fi
else
echo_skipped
fi
echononl " Create sample client configuration ${_client_conf_file}.."
cat << EOF > "$_client_conf_file" 2> $log_file
##############################################
# Sample client-side OpenVPN 2.0 config file #
# for connecting to multi-client server. #
# #
# This configuration can be used by multiple #
# clients, however each client should have #
# its own cert and key files. #
# #
# On Windows, you might want to rename this #
# file so it has a .ovpn extension #
##############################################
# Specify that we are a client and that we
# will be pulling certain config file directives
# from the server.
client
# Use the same setting as you are using on
# the server.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun
# Are we connecting to a TCP or
# UDP server? Use the same setting as
# on the server
proto udp
# The hostname/IP and port of the server.
# You can have multiple remote entries
# to load balance between the servers.
remote $OPENVPN_SERVER $SERVER_PORT udp4
topology subnet
# Keep trying indefinitely to resolve the
# host name of the OpenVPN server. Very useful
# on machines which are not permanently connected
# to the internet such as laptops.
resolv-retry infinite
# Most clients don't need to bind to
# a specific local port number.
nobind
# Try to preserve some state across restarts.
persist-key
persist-tun
# Server CA
<ca>
EOF
_file="${_CA_CERT}"
_found=false
while IFS='' read -r line || [[ -n $line ]]; do
if [[ "$line" =~ "-----BEGIN" ]] ; then
_found=true
fi
if $_found ; then
echo "$line" >> "$_client_conf_file"
fi
if [[ "$line" =~ "-----END" ]]; then
_found=false
fi
done < $_file
cat << EOF >> "$_client_conf_file" 2> $log_file
</ca>
# Client Certificate
<cert>
EOF
_file="${_CLIENT_CERT}"
_found=false
while IFS='' read -r line || [[ -n $line ]]; do
if [[ "$line" =~ "-----BEGIN" ]] ; then
_found=true
fi
if $_found ; then
echo "$line" >> "$_client_conf_file"
fi
if [[ "$line" =~ "-----END" ]]; then
_found=false
fi
done < $_file
cat << EOF >> "$_client_conf_file" 2> $log_file
</cert>
# Client Key
<key>
EOF
_file="${_CLIENT_KEY}"
_found=false
while IFS='' read -r line || [[ -n $line ]]; do
if [[ "$line" =~ "-----BEGIN" ]] ; then
_found=true
fi
if $_found ; then
echo "$line" >> "$_client_conf_file"
fi
if [[ "$line" =~ "-----END" ]]; then
_found=false
fi
done < $_file
cat << EOF >> "$_client_conf_file" 2> $log_file
</key>
# Verify server certificate by checking
# that the certicate has the nsCertType
# field set to "server". This is an
# important precaution to protect against
# a potential attack discussed here:
# http://openvpn.net/howto.html#mitm
#
# To use this feature, you will need to generate
# your server certificates with the nsCertType
# field set to "server". The build-key-server
# script in the easy-rsa folder will do this.
#
# Note!
# The option "ns-cert-type" has been deprecated since
# version 2.4 and will be removed from later distributions.
#
# Use the modern equivalent "remote-cert-tls"
#
;ns-cert-type server
remote-cert-tls server
# If a tls-auth key is used on the server
# then every client must also have the key.
#
# Don't forget to set the 'key-direction' Parameter if using
# Inline Key. Usualy , sever has key direction '0', while client
# has ke direction '1'.
#
key-direction 1
<tls-auth>
EOF
_file="${_TA_KEY}"
_found=false
while IFS='' read -r line || [[ -n $line ]]; do
if [[ "$line" =~ "-----BEGIN" ]] ; then
_found=true
fi
if $_found ; then
echo "$line" >> "$_client_conf_file"
fi
if [[ "$line" =~ "-----END" ]]; then
_found=false
fi
done < $_file
cat << EOF >> "$_client_conf_file" 2> $log_file
</tls-auth>
# Select a cryptographic cipher.
# If the cipher option is used on the server
# then you must also specify it here.
;cipher BF-CBC # Blowfish (default)
;cipher AES-128-CBC # AES
;cipher DES-EDE3-CBC # Triple-DES
EOF
if [[ -n "$SERVER_CIPHER" ]]; then
cat <<EOF >> "$_client_conf_file" 2>> "$log_file"
cipher $SERVER_CIPHER
EOF
else
cat <<EOF >> "$_client_conf_file" 2>> "$log_file"
cipher BF-CBC
EOF
fi
cat <<EOF >> "$_client_conf_file" 2>> "$log_file"
# Enable compression on the VPN link.
# Don't enable this unless it is also
# enabled in the server config file.
;comp-lzo
EOF
if $LZO_COMPRESSION ; then
cat <<EOF >> ${_client_conf_file} 2>> "$log_file"
comp-lzo
EOF
fi
cat <<EOF >> ${_client_conf_file} 2>> "$log_file"
# --auth-nocache
#
# Don't cache --askpass or --auth-user-pass username/passwords in
# virtual memory.
# If specified, this directive will cause OpenVPN to immediately forget
# username/password inputs after they are used. As a result, when OpenVPN
# needs a username/password, it will prompt for input from stdin, which may
# be multiple times during the duration of an OpenVPN session.
#
# When using --auth-nocache in combination with a user/password file
# and --chroot or --daemon, make sure to use an absolute path.
#
#
auth-nocache
# Verbosity level.
# 0 -- quiet except for fatal errors.
# 1 -- mostly quiet, but display non-fatal network errors.
# 3 -- medium output, good for normal operation.
# 9 -- verbose, good for troubleshooting
verb 1
# Setting 'pull' on the client takes care to get the 'push' durectives
# from the server
pull
EOF
if [[ $? -eq 0 ]] ; then
echo_ok
else
echo_failed
#error "$(cat $log_file)"
fi
echo ""
echononl " Create directory '$(dirname "$_target_dir")'.."
if [[ ! -d "$(dirname "$_target_dir")" ]] ; then
mkdir "$(dirname "$_target_dir")" > $log_file 2>&1
if [[ $? -eq 0 ]] ; then
echo_ok
else
echo_failed
fatal "$(cat $log_file)"
fi
else
echo_skipped
fi
_failed=false
echononl " Copy key material into dir '${_target_dir}'.."
if [[ -d "${_target_dir}" ]]; then
mv "${_target_dir}" "${_target_dir}.$_date" > $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
fi
mkdir "${_target_dir}" > $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
cp -a "${_CLIENT_KEY}" "${_target_dir}" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
if [[ -n "$ORG_SHORTCUT" ]]; then
cp -a "$_client_conf_file" "${_target_dir}/${ORG_SHORTCUT}-$(basename $_client_conf_file)" >> $log_file 2>&1
cp -a "$_client_conf_file" "${_target_dir}/${ORG_SHORTCUT} $(basename $_client_conf_file)" >> $log_file 2>&1
else
cp -a "$_client_conf_file" "${_target_dir}/${KEY_CN/VPN-/}-$(basename $_client_conf_file)" >> $log_file 2>&1
fi
if [[ $? -ne 0 ]] ; then
_failed=true
fi
# - For historical reasons
# -
cp -a "$_client_conf_file" "${_target_dir}/client-$(basename $_client_conf_file)" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
cp -a "$_client_conf_file" "${_target_dir}/${_CLIENT_CN}.ovpn"
if [[ $? -ne 0 ]] ; then
_failed=true
fi
cp -a "$_client_conf_file" "${_target_dir}/client-${NEW_KEY_NAME}.conf"
if [[ $? -ne 0 ]] ; then
_failed=true
fi
cp -a "${_CLIENT_CERT}" "${_target_dir}/" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
if [[ -n "$ORG_SHORTCUT" ]]; then
cp -a "${_CA_CERT}" "${_target_dir}/VPN-${ORG_SHORTCUT}-$(basename ${_CA_CERT})" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
cp -a "${_TA_KEY}" "${_target_dir}/VPN-${ORG_SHORTCUT}-$(basename ${_TA_KEY})" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
else
cp -a "${_CA_CERT}" "${_target_dir}/VPN-${KEY_CN/VPN-/}-$(basename ${_CA_CERT})" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
cp -a "${_TA_KEY}" "${_target_dir}/VPN-${KEY_CN/VPN-/}-$(basename ${_TA_KEY})" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
fi
cat << EOF > "${_target_dir}/passwd.txt"
key...............: $(basename "$_CLIENT_KEY")
common name.......: $_CLIENT_CN
password..........: ${KEY_PW}
EOF
if [[ $? -ne 0 ]] ; then
_failed=true
fi
echo "${KEY_PW}" > "${_target_dir}/ovpn_pass"
if [[ $? -ne 0 ]] ; then
_failed=true
fi
chown -R ${user_name}:$user_name "${_home_dir}/VPN" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
if $_failed ; then
echo_failed
error "$(cat $log_file)"
else
echo_ok
fi
# - Create a folder with suffix '.tblk' containing the openvpn configuration in
# - a subfolder 'Contents/Resources' (its MAC OS specific)
# -
# - If the configuration file contains all keys/certs, only the configuration file
# - with its suffix '.ovpn' is needed.
# -
_failed=false
echononl " Create zip archive '${_CLIENT_CN}.tblk.zip' for MAC OS .."
target_macos_tblk_dir="${_target_dir}/${_CLIENT_CN}.tblk"
mkdir "$target_macos_tblk_dir" > $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
mkdir -p "${target_macos_tblk_dir}/Contents/Resources" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
cp -a "$_client_conf_file" "${target_macos_tblk_dir}/Contents/Resources/config.ovpn" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
cd "${_target_dir}" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
chown -R ${user_name}:$user_name "$target_macos_tblk_dir" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
zip -r "${_CLIENT_CN}.tblk.zip" \
"${_CLIENT_CN}.tblk" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
chown ${user_name}:$user_name "${_CLIENT_CN}.tblk.zip" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
rm -r "${target_macos_tblk_dir}" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
_failed=true
fi
if $_failed ; then
echo_failed
error "$(cat $log_file)"
else
echo_ok
fi
info "Key material and OpenVPN config for \033[37m\033[1m${NEW_KEY_NAME}\033[m is stored at '${_home_dir}/VPN'"
clean_up 0