Skip to content

Instantly share code, notes, and snippets.

@qrkourier
Last active November 18, 2023 19:42
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 qrkourier/b9cacf765b2d62817672bc7e6be6bdc3 to your computer and use it in GitHub Desktop.
Save qrkourier/b9cacf765b2d62817672bc7e6be6bdc3 to your computer and use it in GitHub Desktop.
parse or verify a Ziti enrollment token as JWT
#!/usr/bin/env python
# Obtain the Ziti Edge JWT signing pubkey for enrollment tokens by parsing the client API's server certificate.
#
# openssl s_client -connect ziti-edge-controller:443 <>/dev/null \
# |& openssl x509 -noout -pubkey \
# | tee /tmp/client-pubkey.pem
import sys
import jwt
import json
import os
import chardet
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Usage: ziti-jwt.py <jwt> [<signing pubkey>]")
sys.exit(1)
def detect_encoding(file_path):
with open(file_path, 'rb') as file:
data = file.read()
return chardet.detect(data)['encoding']
def get_file_content_or_string(s):
if os.path.isfile(s):
with open(s, 'rb') as file:
return file.read().decode(detect_encoding(s), 'strict').strip()
else:
return s
def parse_verify_jwt(token, key):
claimset = jwt.decode(
jwt=token,
key=key,
algorithms=["ES256", "RS256"],
options={
"verify_signature": True if key else False,
"verify_aud": False,
}
)
return claimset
token = get_file_content_or_string(sys.argv[1])
if len(sys.argv) == 3:
key = get_file_content_or_string(sys.argv[2])
print(f"DEBUG: verifying {token}")
else:
key = None
print(f"DEBUG: parsing {token}")
header = jwt.get_unverified_header(token)
try:
claimset = parse_verify_jwt(token, key)
except jwt.exceptions.InvalidSignatureError:
claimset = parse_verify_jwt(token, None)
signature_valid = False
else:
claimset = parse_verify_jwt(token, key)
if key:
signature_valid = True
else:
signature_valid = False
print(
json.dumps({
"header": header,
"payload": claimset,
"signature_valid": signature_valid,
}, indent=4)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment