Created
April 23, 2022 23:49
-
-
Save ilyaevseev/2a7441dd871305da425dad67438fbfb9 to your computer and use it in GitHub Desktop.
External password authorization script for OpenVPN server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Environment variables: | |
# username (required) | |
# password (optional for all except check) | |
# Usage in openvpn-server.conf: | |
# auth-user-pass-verify "/etc/openvpn/passwd-auth-script" via-env | |
# script-security 3 | |
# verify-client-cert none | |
# username-as-common-name | |
FILE="$(dirname "$0")/passwd-auth-userlist" | |
Fail() { echo "Error: $@" 1>&2; exit 1; } | |
CheckExists() { grep -q "^$NAME:" "$FILE"; } | |
Check() { | |
local A="$(awk -F: '/^'"$NAME"':/ { print $2; exit }' "$FILE")" | |
local B="${A#\$apr1\$}" # ..strip prefix "apr1" | |
local C="${B%\$*}" # ..get salt | |
local D="$(openssl passwd -apr1 -salt "$C" "$password")" | |
test "$A" = "$D" | |
} | |
Add() { | |
local SALT="$(openssl rand -hex 4)" | |
local PASS="$(openssl rand -hex 20)" | |
local HASH="$(openssl passwd -apr1 -salt "$SALT" "$PASS")" | |
umask 027 | |
touch "$FILE" | |
{ grep -v "^$NAME:" "$FILE"; echo "$NAME:$HASH"; } > "$FILE.$$" | |
chown root:openvpn "$FILE.$$" | |
chmod 640 "$FILE.$$" | |
mv "$FILE.$$" "$FILE" | |
echo "PASSWORD: $PASS" | |
} | |
CMD="${1:-check}" | |
NAME="${2:-${username}}" | |
case "$CMD" in | |
check ) CheckExists && Check ;; | |
create ) CheckExists && Fail "user $NAME already exists." || Add ;; | |
replace ) CheckExists || Fail "user $NAME not found."; Add ;; | |
add | update ) Add ;; | |
* ) Fail "wrong command $1" ;; | |
esac | |
## END ## |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment