Skip to content

Instantly share code, notes, and snippets.

@jayme-github
Created February 17, 2023 11:47
Show Gist options
  • Save jayme-github/a8d533300e5313e18725d9cc89bd26e8 to your computer and use it in GitHub Desktop.
Save jayme-github/a8d533300e5313e18725d9cc89bd26e8 to your computer and use it in GitHub Desktop.
Figure out the keypair used to sign a kubernetes service account token
# Get namespace, secret name and JWT "kid" (key ID) of all service-account-token secrets
kubectl get secrets --field-selector type=kubernetes.io/service-account-token \
-o jsonpath='{range .items[*]}{.data.token}{"\n"}{end}' -A |
while read token; do
echo $token | base64 -d | step crypto jwt inspect --insecure | jq -r '[ .payload."kubernetes.io/serviceaccount/namespace", .payload."kubernetes.io/serviceaccount/secret.name", .header.kid] | @tsv'
done
# The key ID references the public-key that needs to be used to validate the signature.
# Compute the kid for a given public-key like:
package main
import (
"crypto"
_ "crypto/sha256"
"crypto/x509"
"encoding/base64"
"fmt"
"k8s.io/client-go/util/keyutil"
"log"
"os"
)
func main() {
publicKeys, err := keyutil.PublicKeysFromFile(os.Args[1])
if err != nil {
log.Fatal(err)
}
for _, pub := range publicKeys {
publicKeyDERBytes, err := x509.MarshalPKIXPublicKey(pub)
if err != nil {
log.Fatal(fmt.Errorf("failed to serialize public key to DER format: %v", err))
}
hasher := crypto.SHA256.New()
hasher.Write(publicKeyDERBytes)
publicKeyDERHash := hasher.Sum(nil)
keyID := base64.RawURLEncoding.EncodeToString(publicKeyDERHash)
log.Println(keyID)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment