Skip to content

Commit

Permalink
create jwt token inside ssh service via bash instead of npm
Browse files Browse the repository at this point in the history
  • Loading branch information
Schnitzel authored and rocketeerbkw committed Feb 7, 2020
1 parent 7cc2bb4 commit 9aa9076
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 9 deletions.
6 changes: 1 addition & 5 deletions services/ssh/Dockerfile
Expand Up @@ -28,7 +28,7 @@ ENV LAGOON=ssh \
COPY services/ssh/libnss-mysql-1.5.tar.gz /tmp/libnss-mysql-1.5.tar.gz

RUN apt-get update \
&& apt-get install -y curl build-essential libmysqlclient-dev ssh curl npm vim jq \
&& apt-get install -y curl build-essential libmysqlclient-dev ssh curl vim jq \
&& ln -s /usr/lib/x86_64-linux-gnu/libmysqlclient.so /usr/lib/libmysqlclient.so \
&& mkdir /tmp/libnss-mysql \
&& tar -xzf /tmp/libnss-mysql-1.5.tar.gz -C /tmp/libnss-mysql --strip-components=1 \
Expand All @@ -52,10 +52,6 @@ RUN curl -L https://github.com/krallin/tini/releases/download/v0.18.0/tini -o /s
# Reproduce behavior of Alpine: Run Bash as sh
RUN rm -f /bin/sh && ln -s /bin/bash /bin/sh

# Needed for jwt generation
RUN npm config set unsafe-perm true \
&& npm -g install jwtgen

COPY services/ssh/etc/ /etc/
COPY services/ssh/home/ /home/

Expand Down
45 changes: 41 additions & 4 deletions services/ssh/create_60_sec_jwt.sh
@@ -1,12 +1,49 @@
#!/usr/bin/env bash
set -o pipefail

header_template='{
"typ": "JWT",
"alg": "HS256",
"iss": "ssh Bash JWT Generator",
"sub": "ssh"
}'

build_header() {
jq -c \
--arg iat_str "$(date +%s)" \
--arg alg "${1:-HS256}" \
"
(\$iat_str | tonumber) as \$iat
| .alg = \$alg
| .iat = \$iat
| .exp = (\$iat + ${4:-60})
" <<<"$header_template" | tr -d '\n'
}

b64enc() { openssl enc -base64 -A | tr '+/' '-_' | tr -d '='; }
json() { jq -c . | LC_CTYPE=C tr -d '\n'; }
hs_sign() { openssl dgst -binary -sha"${1}" -hmac "$2"; }
rs_sign() { openssl dgst -binary -sha"${1}" -sign <(printf '%s\n' "$2"); }

sign() {
local algo payload header sig secret=$3
algo=${1:-RS256}; algo=${algo^^}
header=$(build_header "$algo") || return
payload=${2:-$test_payload}
signed_content="$(json <<<"$header" | b64enc).$(json <<<"$payload" | b64enc)"
case $algo in
HS*) sig=$(printf %s "$signed_content" | hs_sign "${algo#HS}" "$secret" | b64enc) ;;
RS*) sig=$(printf %s "$signed_content" | rs_sign "${algo#RS}" "$secret" | b64enc) ;;
*) echo "Unknown algorithm" >&2; return 1 ;;
esac
printf '%s.%s\n' "${signed_content}" "${sig}"
}

set -euo pipefail

PAYLOAD='{
"role": "admin",
"iss": "ssh Bash JWT Generator",
"aud": "'$JWTAUDIENCE'",
"sub": "ssh"
"aud": "'$JWTAUDIENCE'"
}'

/usr/bin/nodejs /usr/local/bin/jwtgen -a HS256 -e 60 -s "${JWTSECRET}" --claims "${PAYLOAD}" $@
sign hs256 "${PAYLOAD}" "${JWTSECRET}" 60

0 comments on commit 9aa9076

Please sign in to comment.