Skip to content

Instantly share code, notes, and snippets.

@mohclips
Created February 27, 2022 21:05
Show Gist options
  • Save mohclips/94603f501124fd38e2f64e066740f9fa to your computer and use it in GitHub Desktop.
Save mohclips/94603f501124fd38e2f64e066740f9fa to your computer and use it in GitHub Desktop.
pull apart kubernetes jwt tokens
#!/bin/bash
assert() { if [[ $1 != $2 ]]; then echo "assert" $3; exit; fi }
decodeJWT() {
jwt=$1
# trick from https://gist.github.com/rolandyoung/176dd310a6948e094be6#file-verifytoken-sh
# basically the token is split with a '.' delimeter
input=${jwt%.*} # delete shortest match of substr from back of str
encHdr=${input%.*} # delete shortest match of substr from back of str
encPayload=${input#*.} # delete shortest match of substr
encSig=${jwt##*.} # delete longest match of substr
assert $jwt "$encHdr.$encPayload.$encSig" "failed to decompose jwt"
echo -n $encPayload | base64 -d 2>/dev/null
}
# usage
# ./jwt-decode.sh $(kubectl -n hackme-ns get secrets hackme-sa-token-5wt6c -oyaml | yq .data.token | base64 -d)
# TOKEN is the base64 -d returns from the secret
TOKEN=$1
decodeJWT "$TOKEN"
@mohclips
Copy link
Author

Example:

root@test-nginx:/# curl -LO https://gist.github.com/mohclips/94603f501124fd38e2f64e066740f9fa/raw/cada6ec7317d6ca446304545aebc4550ff78baa6/jwt-decode.sh  % 

root@test-nginx:/# chmod +x jwt-decode.sh

root@test-nginx:/# ./jwt-decode.sh $(cat /var/run/secrets/kubernetes.io/serviceaccount/token) | sed -e 's/,/,\n/g'
{"aud":["https://kubernetes.default.svc.cluster.local"],
"exp":1677532089,
"iat":1645996089,
"iss":"https://kubernetes.default.svc.cluster.local",
"kubernetes.io":{"namespace":"hackme-ns",
"pod":{"name":"test-nginx",
"uid":"05e44891-1c30-4cf8-ba31-38c137405f24"},
"serviceaccount":{"name":"hackme-sa",
"uid":"30270a28-cfa6-434c-87fe-c2b06773b72b"},
"warnafter":1645999696},
"nbf":1645996089,
"sub":"system:serviceaccount:hackme-ns:hackme-sa"}root@test-nginx:/# 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment