Skip to content

Instantly share code, notes, and snippets.

@kedazo
Last active January 8, 2019 07:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kedazo/8baf563622e509691d8043980ebb77a1 to your computer and use it in GitHub Desktop.
Save kedazo/8baf563622e509691d8043980ebb77a1 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Arguments: private-key-file username [URL]
echo "$0 - RPCv2 authenticator"
KEYFILE=$1
if [ "${KEYFILE}x" == "x" ]; then
KEYFILE=./user.key
fi
USERNAME=$2
if [ "${USERAME}x" == "x" ]; then
USERNAME="username@test.tld"
fi
URL=$3
if [ "${URL}x" == "x" ]; then
URL="https://127.0.0.1:9501/0/auth"
fi
echo "* Arguments:"
echo " Username: ${USERNAME}"
echo " URL: ${URL}"
echo " Using RSA key ${KEYFILE}"
if [ -f ${KEYFILE} ]; then
echo "* Key file exists."
else
echo "* Missing key file, aborting."
exit 1
fi
if [ ! -r ${KEYFILE} ]; then
echo "* ${KEYFILE} is not readable."
exit 1
fi
# this must be removed as soon as we exit
COOKIE_JAR=./curl_cookie_jar.data
function cleanup()
{
echo "* cookies saved to ${COOKIE_JAR}"
return # keep cookies file for futher usage
echo "* cleaning up"
rm -fv ${COOKIE_JAR}
}
trap cleanup EXIT
# Arguments: $0 JSON string
function doJSonRequest()
{
JSON="$1"
# save and read cookies from JAR
CURLARGS="--silent --insecure -b ${COOKIE_JAR} -c ${COOKIE_JAR}"
curl "${URL}" ${CURLARGS} -XPOST -d"${JSON}"
}
function readJSon()
{
# args: stdin: json
# $1 : param-name to extract
grep -Po "(?<=\"$1\": \")[^\"]*"
}
# Step0: cleanup
cleanup
# Step1: login request
echo "*"
echo "* request login on RPC"
echo "*"
LOGIN_REPLY=$(doJSonRequest "{\"operation\":\"login\",\"username\":\"${USERNAME}\"}")
REQSTATUS=$(echo ${LOGIN_REPLY} | readJSon "requestStatus")
ERRORSTR=$(echo ${LOGIN_REPLY} | readJSon "errorString")
CHALLENGE=$(echo ${LOGIN_REPLY} | readJSon "challenge")
echo "login reply (status: ${REQSTATUS})"
if [ -n "$ERRORSTR" ]; then
echo "login error: ${ERRORSTR}"
exit 1
fi
# Step2: SHA256-RSA sign the challenge and send it back
echo "*"
echo "* response to challenge (${CHALLENGE})"
echo "*"
# create an SHA256-RSA signature using user's privkey, encoded in base64
SIGNATURE=$(echo -n ${CHALLENGE} | openssl sha256 -sha256 -sign ${KEYFILE} | base64)
RESP_REPLY=$(doJSonRequest "{\"operation\":\"response\",\"signature\":\"${SIGNATURE}\"}")
REQSTATUS=$(echo ${RESP_REPLY} | readJSon "requestStatus")
ERRORSTR=$(echo ${RESP_REPLY} | readJSon "errorString")
echo "response reply (status: ${REQSTATUS})"
if [ -n "$ERRORSTR" ]; then
echo "login error: ${ERRORSTR}"
exit 1
fi
if [ "${REQSTATUS}" == "ok" ]; then
echo "* ${USERNAME} authenticated successfully."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment