-
Notifications
You must be signed in to change notification settings - Fork 1
/
TestJWT.py
181 lines (153 loc) · 6.09 KB
/
TestJWT.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import json
import sys
import signatures
import utils
from cryptography.hazmat.primitives.serialization import (
load_pem_public_key, load_pem_private_key
)
from cryptography.hazmat.backends import default_backend
class TestJWT:
"""
Contains JWT under test
"""
def __init__(self):
self.is_json = True
self.header = {}
self.payload = {}
def get_payload(self):
if self.is_json:
return self.payload
return self.payload['default']
def set_payload(self, payload):
if utils.is_dict(payload):
self.payload = payload
else:
self.is_json = False
self.payload = {"default": payload}
@staticmethod
def split_jwt(ser_token):
return ser_token.split(".", 3)
@staticmethod
def deserialize(ser_token: str):
"""
Builds a TestJWT from a serialized JWT representation
:param ser_token: serialized token
:return: TestJWT instance
"""
tok1, tok2, sig = TestJWT.split_jwt(ser_token)
head = utils.base64url_decode(tok1)
payload = utils.base64url_decode(tok2)
jwt = TestJWT()
jwt.original_jwt = ser_token
# noinspection PyBroadException
try:
jwt.header = json.loads(head)
jwt_payload = json.loads(payload)
jwt.set_payload(jwt_payload)
except:
jwt.set_payload(utils.force_unicode(payload))
return jwt
def show_token(self):
"""
Print token
:return:
"""
print("\nIs JSON: {}".format(self.is_json))
print("\nToken header:")
print(json.dumps(self.header, indent=4, ensure_ascii=True))
for i in self.header:
"-> {} = {}".format(i, self.header[i])
print("\nToken payload:")
if self.is_json:
print(json.dumps(self.get_payload(), indent=4, ensure_ascii=True))
for i in self.get_payload():
print("-> {} = {}".format(i, self.get_payload()[i]))
else:
print(self.get_payload())
def get_algorithm(self):
return self.header['alg']
def set_algorithm(self, new_alg):
self.header['alg'] = new_alg
@staticmethod
def build_section(dict_section):
"""
Builds a JWT section (header or payload) by properly encoding content.
:param dict_section: JSON (dict) or plain text (str) content to be encoded
:return: JWT encoded section
"""
if utils.is_dict(dict_section):
new_section = utils.base64url_encode(utils.force_bytes(json.dumps(dict_section, separators=(",", ":"))))
else:
new_section = utils.base64url_encode(utils.force_bytes(dict_section))
return new_section
def build_token_without_signature(self):
return TestJWT.build_section(self.header) + utils.force_bytes('.') + TestJWT.build_section(self.get_payload())
def build_token(self, key=None):
content_to_sign = self.build_token_without_signature()
return content_to_sign + utils.force_bytes('.') + signatures.sign(self.get_algorithm(), content_to_sign,
key=key)
def verify_signature(self, key, expected_sig):
alg = self.header['alg']
print("Verify signature using alg {}".format(alg))
if alg is None:
print("Signature algorithm not set")
return False
if str.capitalize(alg) == "NONE":
return True
alg = self.get_algorithm()
return signatures.verify(alg, self.build_token_without_signature(), key, utils.force_bytes(expected_sig))
def compute_signature(self, key):
alg = self.get_algorithm()
print("Computing signature using alg {}".format(alg))
if alg is None:
print("Signature algorithm not set")
return False
if str.capitalize(alg) == "NONE":
return self.build_token_without_signature()
# TODO reuse build_section
content_to_sign = utils.base64url_encode(
utils.force_bytes(json.dumps(self.header, separators=(",", ":")))) + utils.force_bytes(
".") + utils.base64url_encode(utils.force_bytes(json.dumps(self.payload, separators=(",", ":"))))
return signatures.sign(alg, content_to_sign, key=key)
def get_arg_value(param: str):
name_value = param.split("=", 2)
if len(name_value) != 2:
return None
return name_value[1]
def print_help():
print("\n\nUsage: TestJWT jwt_token [-s=secret|-p=path_to_pubkey_pem_file]\n")
def parse_and_validate():
if len(sys.argv) < 2:
print_help()
if len(sys.argv) >= 2:
serial_jwt = sys.argv[1]
_, _, signature = TestJWT.split_jwt(serial_jwt)
jwt: TestJWT = TestJWT.deserialize(serial_jwt)
jwt.show_token()
if len(sys.argv) == 3:
params: str = sys.argv[2]
param_val = get_arg_value(params)
if param_val is None:
print_help()
return
verified_sig = False
if params.startswith("-s") and param_val:
secret = param_val
verified_sig = jwt.verify_signature(secret, signature)
elif params.startswith("-p") and param_val:
key = load_pem_public_key(utils.read_pem_file(param_val), default_backend())
verified_sig = jwt.verify_signature(key, utils.base64url_decode(signature))
elif params.startswith("-jwks") and param_val:
jwks = json.loads(utils.read_file(param_val, strip_newline=True, join_lines=True))
key = utils.rsa_jwks_to_pubkey(jwks)
verified_sig = jwt.verify_signature(key, utils.base64url_decode(signature))
# TODO add support to verify signature if jwk is included in header
else:
print_help()
return
if verified_sig:
print("Signature verified")
else:
print("Signature verification FAILED !!")
if __name__ == '__main__':
parse_and_validate()