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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
|
#pragma once
#define PICOJSON_USE_INT64
#include "picojson.h"
#include "base.h"
#include <set>
#include <chrono>
#include <unordered_map>
#include <memory>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/pem.h>
#include <openssl/ec.h>
#include <openssl/err.h>
//If openssl version less than 1.1
#if OPENSSL_VERSION_NUMBER < 269484032
#define OPENSSL10
#endif
#ifndef JWT_CLAIM_EXPLICIT
#define JWT_CLAIM_EXPLICIT 0
#endif
namespace jwt {
using date = std::chrono::system_clock::time_point;
struct signature_verification_exception : public std::runtime_error {
signature_verification_exception()
: std::runtime_error("signature verification failed")
{}
explicit signature_verification_exception(const std::string& msg)
: std::runtime_error(msg)
{}
explicit signature_verification_exception(const char* msg)
: std::runtime_error(msg)
{}
};
struct signature_generation_exception : public std::runtime_error {
signature_generation_exception()
: std::runtime_error("signature generation failed")
{}
explicit signature_generation_exception(const std::string& msg)
: std::runtime_error(msg)
{}
explicit signature_generation_exception(const char* msg)
: std::runtime_error(msg)
{}
};
struct rsa_exception : public std::runtime_error {
explicit rsa_exception(const std::string& msg)
: std::runtime_error(msg)
{}
explicit rsa_exception(const char* msg)
: std::runtime_error(msg)
{}
};
struct ecdsa_exception : public std::runtime_error {
explicit ecdsa_exception(const std::string& msg)
: std::runtime_error(msg)
{}
explicit ecdsa_exception(const char* msg)
: std::runtime_error(msg)
{}
};
struct token_verification_exception : public std::runtime_error {
token_verification_exception()
: std::runtime_error("token verification failed")
{}
explicit token_verification_exception(const std::string& msg)
: std::runtime_error("token verification failed: " + msg)
{}
};
namespace algorithm {
/**
* "none" algorithm.
*
* Returns and empty signature and checks if the given signature is empty.
*/
struct none {
/// Return an empty string
std::string sign(const std::string&) const {
return "";
}
/// Check if the given signature is empty. JWT's with "none" algorithm should not contain a signature.
void verify(const std::string&, const std::string& signature) const {
if (!signature.empty())
throw signature_verification_exception();
}
/// Get algorithm name
std::string name() const {
return "none";
}
};
/**
* Base class for HMAC family of algorithms
*/
struct hmacsha {
/**
* Construct new hmac algorithm
* \param key Key to use for HMAC
* \param md Pointer to hash function
* \param name Name of the algorithm
*/
hmacsha(std::string key, const EVP_MD*(*md)(), const std::string& name)
: secret(std::move(key)), md(md), alg_name(name)
{}
/**
* Sign jwt data
* \param data The data to sign
* \return HMAC signature for the given data
* \throws signature_generation_exception
*/
std::string sign(const std::string& data) const {
std::string res;
res.resize(EVP_MAX_MD_SIZE);
unsigned int len = res.size();
if (HMAC(md(), secret.data(), secret.size(), (const unsigned char*)data.data(), data.size(), (unsigned char*)res.data(), &len) == nullptr)
throw signature_generation_exception();
res.resize(len);
return res;
}
/**
* Check if signature is valid
* \param data The data to check signature against
* \param signature Signature provided by the jwt
* \throws signature_verification_exception If the provided signature does not match
*/
void verify(const std::string& data, const std::string& signature) const {
try {
auto res = sign(data);
bool matched = true;
for (size_t i = 0; i < std::min<size_t>(res.size(), signature.size()); i++)
if (res[i] != signature[i])
matched = false;
if (res.size() != signature.size())
matched = false;
if (!matched)
throw signature_verification_exception();
}
catch (const signature_generation_exception&) {
throw signature_verification_exception();
}
}
/**
* Returns the algorithm name provided to the constructor
* \return Algorithmname
*/
std::string name() const {
return alg_name;
}
private:
/// HMAC secrect
const std::string secret;
/// HMAC hash generator
const EVP_MD*(*md)();
/// Algorithmname
const std::string alg_name;
};
/**
* Base class for RSA family of algorithms
*/
struct rsa {
/**
* Construct new rsa algorithm
* \param public_key RSA public key in PEM format
* \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
* \param md Pointer to hash function
* \param name Name of the algorithm
*/
rsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, const std::string& private_key_password, const EVP_MD*(*md)(), const std::string& name)
: md(md), alg_name(name)
{
std::unique_ptr<BIO, decltype(&BIO_free_all)> pubkey_bio(BIO_new(BIO_s_mem()), BIO_free_all);
if ((size_t)BIO_write(pubkey_bio.get(), public_key.data(), public_key.size()) != public_key.size())
throw rsa_exception("failed to load public key: bio_write failed");
pkey.reset(PEM_read_bio_PUBKEY(pubkey_bio.get(), nullptr, nullptr, (void*)public_key_password.c_str()), EVP_PKEY_free);
if (!pkey)
throw rsa_exception("failed to load public key: PEM_read_bio_PUBKEY failed");
if (!private_key.empty()) {
std::unique_ptr<BIO, decltype(&BIO_free_all)> privkey_bio(BIO_new(BIO_s_mem()), BIO_free_all);
if ((size_t)BIO_write(privkey_bio.get(), private_key.data(), private_key.size()) != private_key.size())
throw rsa_exception("failed to load private key: bio_write failed");
RSA* privkey = PEM_read_bio_RSAPrivateKey(privkey_bio.get(), nullptr, nullptr, (void*)private_key_password.c_str());
if (privkey == nullptr)
throw rsa_exception("failed to load private key: PEM_read_bio_RSAPrivateKey failed");
if (EVP_PKEY_assign_RSA(pkey.get(), privkey) == 0) {
RSA_free(privkey);
throw rsa_exception("failed to load private key: EVP_PKEY_assign_RSA failed");
}
}
}
/**
* Sign jwt data
* \param data The data to sign
* \return RSA signature for the given data
* \throws signature_generation_exception
*/
std::string sign(const std::string& data) const {
#ifdef OPENSSL10
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)> ctx(EVP_MD_CTX_create(), EVP_MD_CTX_destroy);
#else
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> ctx(EVP_MD_CTX_create(), EVP_MD_CTX_free);
#endif
if (!ctx)
throw signature_generation_exception("failed to create signature: could not create context");
if (!EVP_SignInit(ctx.get(), md()))
throw signature_generation_exception("failed to create signature: SignInit failed");
std::string res;
res.resize(EVP_PKEY_size(pkey.get()));
unsigned int len = 0;
if (!EVP_SignUpdate(ctx.get(), data.data(), data.size()))
throw signature_generation_exception();
if (!EVP_SignFinal(ctx.get(), (unsigned char*)res.data(), &len, pkey.get()))
throw signature_generation_exception();
res.resize(len);
return res;
}
/**
* Check if signature is valid
* \param data The data to check signature against
* \param signature Signature provided by the jwt
* \throws signature_verification_exception If the provided signature does not match
*/
void verify(const std::string& data, const std::string& signature) const {
#ifdef OPENSSL10
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)> ctx(EVP_MD_CTX_create(), EVP_MD_CTX_destroy);
#else
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> ctx(EVP_MD_CTX_create(), EVP_MD_CTX_free);
#endif
if (!ctx)
throw signature_verification_exception("failed to verify signature: could not create context");
if (!EVP_VerifyInit(ctx.get(), md()))
throw signature_verification_exception("failed to verify signature: VerifyInit failed");
if (!EVP_VerifyUpdate(ctx.get(), data.data(), data.size()))
throw signature_verification_exception("failed to verify signature: VerifyUpdate failed");
if (!EVP_VerifyFinal(ctx.get(), (const unsigned char*)signature.data(), signature.size(), pkey.get()))
throw signature_verification_exception();
}
/**
* Returns the algorithm name provided to the constructor
* \return Algorithmname
*/
std::string name() const {
return alg_name;
}
private:
/// OpenSSL structure containing converted keys
std::shared_ptr<EVP_PKEY> pkey;
/// Hash generator
const EVP_MD*(*md)();
/// Algorithmname
const std::string alg_name;
};
/**
* Base class for ECDSA family of algorithms
*/
struct ecdsa {
/**
* Construct new ecdsa algorithm
* \param public_key ECDSA public key in PEM format
* \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
* \param md Pointer to hash function
* \param name Name of the algorithm
*/
ecdsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, const std::string& private_key_password, const EVP_MD*(*md)(), const std::string& name)
: md(md), alg_name(name)
{
if (private_key.empty()) {
std::unique_ptr<BIO, decltype(&BIO_free_all)> pubkey_bio(BIO_new(BIO_s_mem()), BIO_free_all);
if ((size_t)BIO_write(pubkey_bio.get(), public_key.data(), public_key.size()) != public_key.size())
throw ecdsa_exception("failed to load public key: bio_write failed");
pkey.reset(PEM_read_bio_EC_PUBKEY(pubkey_bio.get(), nullptr, nullptr, (void*)public_key_password.c_str()), EC_KEY_free);
if (!pkey)
throw ecdsa_exception("failed to load public key: PEM_read_bio_EC_PUBKEY failed");
} else {
std::unique_ptr<BIO, decltype(&BIO_free_all)> privkey_bio(BIO_new(BIO_s_mem()), BIO_free_all);
if ((size_t)BIO_write(privkey_bio.get(), private_key.data(), private_key.size()) != private_key.size())
throw ecdsa_exception("failed to load private key: bio_write failed");
pkey.reset(PEM_read_bio_ECPrivateKey(privkey_bio.get(), nullptr, nullptr, (void*)private_key_password.c_str()), EC_KEY_free);
if (!pkey)
throw ecdsa_exception("failed to load private key: PEM_read_bio_RSAPrivateKey failed");
}
if(EC_KEY_check_key(pkey.get()) == 0)
throw ecdsa_exception("failed to load key: key is invalid");
}
/**
* Sign jwt data
* \param data The data to sign
* \return ECDSA signature for the given data
* \throws signature_generation_exception
*/
std::string sign(const std::string& data) const {
const std::string hash = generate_hash(data);
std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)>
sig(ECDSA_do_sign((const unsigned char*)hash.data(), hash.size(), pkey.get()), ECDSA_SIG_free);
if(!sig)
throw signature_generation_exception();
#ifdef OPENSSL10
return bn2raw(sig->r) + bn2raw(sig->s);
#else
const BIGNUM *r;
const BIGNUM *s;
ECDSA_SIG_get0(sig.get(), &r, &s);
return bn2raw(r) + bn2raw(s);
#endif
}
/**
* Check if signature is valid
* \param data The data to check signature against
* \param signature Signature provided by the jwt
* \throws signature_verification_exception If the provided signature does not match
*/
void verify(const std::string& data, const std::string& signature) const {
const std::string hash = generate_hash(data);
auto r = raw2bn(signature.substr(0, signature.size() / 2));
auto s = raw2bn(signature.substr(signature.size() / 2));
#ifdef OPENSSL10
ECDSA_SIG sig;
sig.r = r.get();
sig.s = s.get();
if(ECDSA_do_verify((const unsigned char*)hash.data(), hash.size(), &sig, pkey.get()) != 1)
throw signature_verification_exception("Invalid signature");
#else
ECDSA_SIG *sig = ECDSA_SIG_new();
ECDSA_SIG_set0(sig, r.get(), s.get());
if(ECDSA_do_verify((const unsigned char*)hash.data(), hash.size(), sig, pkey.get()) != 1)
throw signature_verification_exception("Invalid signature");
#endif
}
/**
* Returns the algorithm name provided to the constructor
* \return Algorithmname
*/
std::string name() const {
return alg_name;
}
private:
/**
* Convert a OpenSSL BIGNUM to a std::string
* \param bn BIGNUM to convert
* \return bignum as string
*/
#ifdef OPENSSL10
static std::string bn2raw(BIGNUM* bn)
#else
static std::string bn2raw(const BIGNUM* bn)
#endif
{
std::string res;
res.resize(BN_num_bytes(bn));
BN_bn2bin(bn, (unsigned char*)res.data());
if(res.size()%2 == 1 && res[0] == 0x00)
return res.substr(1);
return res;
}
/**
* Convert an std::string to a OpenSSL BIGNUM
* \param raw String to convert
* \return BIGNUM representation
*/
static std::unique_ptr<BIGNUM, decltype(&BN_free)> raw2bn(const std::string& raw) {
if(static_cast<uint8_t>(raw[0]) >= 0x80) {
std::string str(1, 0x00);
str += raw;
return std::unique_ptr<BIGNUM, decltype(&BN_free)>(BN_bin2bn((const unsigned char*)str.data(), str.size(), nullptr), BN_free);
}
return std::unique_ptr<BIGNUM, decltype(&BN_free)>(BN_bin2bn((const unsigned char*)raw.data(), raw.size(), nullptr), BN_free);
}
/**
* Hash the provided data using the hash function specified in constructor
* \param data Data to hash
* \return Hash of data
*/
std::string generate_hash(const std::string& data) const {
#ifdef OPENSSL10
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)> ctx(EVP_MD_CTX_create(), &EVP_MD_CTX_destroy);
#else
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> ctx(EVP_MD_CTX_new(), EVP_MD_CTX_free);
#endif
if(EVP_DigestInit(ctx.get(), md()) == 0)
throw signature_generation_exception("EVP_DigestInit failed");
if(EVP_DigestUpdate(ctx.get(), data.data(), data.size()) == 0)
throw signature_generation_exception("EVP_DigestUpdate failed");
unsigned int len = 0;
std::string res;
res.resize(EVP_MD_CTX_size(ctx.get()));
if(EVP_DigestFinal(ctx.get(), (unsigned char*)res.data(), &len) == 0)
throw signature_generation_exception("EVP_DigestFinal failed");
res.resize(len);
return res;
}
/// OpenSSL struct containing keys
std::shared_ptr<EC_KEY> pkey;
/// Hash generator function
const EVP_MD*(*md)();
/// Algorithmname
const std::string alg_name;
};
/**
* Base class for PSS-RSA family of algorithms
*/
struct pss {
/**
* Construct new pss algorithm
* \param public_key RSA public key in PEM format
* \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
* \param md Pointer to hash function
* \param name Name of the algorithm
*/
pss(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, const std::string& private_key_password, const EVP_MD*(*md)(), const std::string& name)
: md(md), alg_name(name)
{
std::unique_ptr<BIO, decltype(&BIO_free_all)> pubkey_bio(BIO_new(BIO_s_mem()), BIO_free_all);
if ((size_t)BIO_write(pubkey_bio.get(), public_key.data(), public_key.size()) != public_key.size())
throw rsa_exception("failed to load public key: bio_write failed");
pkey.reset(PEM_read_bio_PUBKEY(pubkey_bio.get(), nullptr, nullptr, (void*)public_key_password.c_str()), EVP_PKEY_free);
if (!pkey)
throw rsa_exception("failed to load public key: PEM_read_bio_PUBKEY failed");
if (!private_key.empty()) {
std::unique_ptr<BIO, decltype(&BIO_free_all)> privkey_bio(BIO_new(BIO_s_mem()), BIO_free_all);
if ((size_t)BIO_write(privkey_bio.get(), private_key.data(), private_key.size()) != private_key.size())
throw rsa_exception("failed to load private key: bio_write failed");
RSA* privkey = PEM_read_bio_RSAPrivateKey(privkey_bio.get(), nullptr, nullptr, (void*)private_key_password.c_str());
if (privkey == nullptr)
throw rsa_exception("failed to load private key: PEM_read_bio_RSAPrivateKey failed");
if (EVP_PKEY_assign_RSA(pkey.get(), privkey) == 0) {
RSA_free(privkey);
throw rsa_exception("failed to load private key: EVP_PKEY_assign_RSA failed");
}
}
}
/**
* Sign jwt data
* \param data The data to sign
* \return ECDSA signature for the given data
* \throws signature_generation_exception
*/
std::string sign(const std::string& data) const {
auto hash = this->generate_hash(data);
std::unique_ptr<RSA, decltype(&RSA_free)> key(EVP_PKEY_get1_RSA(pkey.get()), RSA_free);
const int size = RSA_size(key.get());
std::string padded(size, 0x00);
if (!RSA_padding_add_PKCS1_PSS_mgf1(key.get(), (unsigned char*)padded.data(), (const unsigned char*)hash.data(), md(), md(), -1))
throw signature_generation_exception("failed to create signature: RSA_padding_add_PKCS1_PSS_mgf1 failed");
std::string res(size, 0x00);
if (RSA_private_encrypt(size, (const unsigned char*)padded.data(), (unsigned char*)res.data(), key.get(), RSA_NO_PADDING) < 0)
throw signature_generation_exception("failed to create signature: RSA_private_encrypt failed");
return res;
}
/**
* Check if signature is valid
* \param data The data to check signature against
* \param signature Signature provided by the jwt
* \throws signature_verification_exception If the provided signature does not match
*/
void verify(const std::string& data, const std::string& signature) const {
auto hash = this->generate_hash(data);
std::unique_ptr<RSA, decltype(&RSA_free)> key(EVP_PKEY_get1_RSA(pkey.get()), RSA_free);
const int size = RSA_size(key.get());
std::string sig(size, 0x00);
if(!RSA_public_decrypt(signature.size(), (const unsigned char*)signature.data(), (unsigned char*)sig.data(), key.get(), RSA_NO_PADDING))
throw signature_verification_exception("Invalid signature");
if(!RSA_verify_PKCS1_PSS_mgf1(key.get(), (const unsigned char*)hash.data(), md(), md(), (const unsigned char*)sig.data(), -1))
throw signature_verification_exception("Invalid signature");
}
/**
* Returns the algorithm name provided to the constructor
* \return Algorithmname
*/
std::string name() const {
return alg_name;
}
private:
/**
* Hash the provided data using the hash function specified in constructor
* \param data Data to hash
* \return Hash of data
*/
std::string generate_hash(const std::string& data) const {
#ifdef OPENSSL10
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)> ctx(EVP_MD_CTX_create(), &EVP_MD_CTX_destroy);
#else
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> ctx(EVP_MD_CTX_new(), EVP_MD_CTX_free);
#endif
if(EVP_DigestInit(ctx.get(), md()) == 0)
throw signature_generation_exception("EVP_DigestInit failed");
if(EVP_DigestUpdate(ctx.get(), data.data(), data.size()) == 0)
throw signature_generation_exception("EVP_DigestUpdate failed");
unsigned int len = 0;
std::string res;
res.resize(EVP_MD_CTX_size(ctx.get()));
if(EVP_DigestFinal(ctx.get(), (unsigned char*)res.data(), &len) == 0)
throw signature_generation_exception("EVP_DigestFinal failed");
res.resize(len);
return res;
}
/// OpenSSL structure containing keys
std::shared_ptr<EVP_PKEY> pkey;
/// Hash generator function
const EVP_MD*(*md)();
/// Algorithmname
const std::string alg_name;
};
/**
* HS256 algorithm
*/
struct hs256 : public hmacsha {
/**
* Construct new instance of algorithm
* \param key HMAC signing key
*/
explicit hs256(std::string key)
: hmacsha(std::move(key), EVP_sha256, "HS256")
{}
};
/**
* HS384 algorithm
*/
struct hs384 : public hmacsha {
/**
* Construct new instance of algorithm
* \param key HMAC signing key
*/
explicit hs384(std::string key)
: hmacsha(std::move(key), EVP_sha384, "HS384")
{}
};
/**
* HS512 algorithm
*/
struct hs512 : public hmacsha {
/**
* Construct new instance of algorithm
* \param key HMAC signing key
*/
explicit hs512(std::string key)
: hmacsha(std::move(key), EVP_sha512, "HS512")
{}
};
/**
* RS256 algorithm
*/
struct rs256 : public rsa {
/**
* Construct new instance of algorithm
* \param public_key RSA public key in PEM format
* \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
*/
rs256(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "")
: rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "RS256")
{}
};
/**
* RS384 algorithm
*/
struct rs384 : public rsa {
/**
* Construct new instance of algorithm
* \param public_key RSA public key in PEM format
* \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
*/
rs384(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "")
: rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "RS384")
{}
};
/**
* RS512 algorithm
*/
struct rs512 : public rsa {
/**
* Construct new instance of algorithm
* \param public_key RSA public key in PEM format
* \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
*/
rs512(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "")
: rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "RS512")
{}
};
/**
* ES256 algorithm
*/
struct es256 : public ecdsa {
/**
* Construct new instance of algorithm
* \param public_key ECDSA public key in PEM format
* \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
*/
es256(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "")
: ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "ES256")
{}
};
/**
* ES384 algorithm
*/
struct es384 : public ecdsa {
/**
* Construct new instance of algorithm
* \param public_key ECDSA public key in PEM format
* \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
*/
es384(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "")
: ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "ES384")
{}
};
/**
* ES512 algorithm
*/
struct es512 : public ecdsa {
/**
* Construct new instance of algorithm
* \param public_key ECDSA public key in PEM format
* \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
*/
es512(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "")
: ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "ES512")
{}
};
/**
* PS256 algorithm
*/
struct ps256 : public pss {
/**
* Construct new instance of algorithm
* \param public_key RSA public key in PEM format
* \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
*/
ps256(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "")
: pss(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "PS256")
{}
};
/**
* PS384 algorithm
*/
struct ps384 : public pss {
/**
* Construct new instance of algorithm
* \param public_key RSA public key in PEM format
* \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
*/
ps384(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "")
: pss(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "PS384")
{}
};
/**
* PS512 algorithm
*/
struct ps512 : public pss {
/**
* Construct new instance of algorithm
* \param public_key RSA public key in PEM format
* \param private_key RSA private key or empty string if not available. If empty, signing will always fail.
* \param public_key_password Password to decrypt public key pem.
* \param privat_key_password Password to decrypt private key pem.
*/
ps512(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "")
: pss(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "PS512")
{}
};
}
/**
* Convenience wrapper for JSON value
*/
class claim {
picojson::value val;
public:
enum class type {
null,
boolean,
number,
string,
array,
object,
int64
};
claim()
: val()
{}
#if JWT_CLAIM_EXPLICIT
explicit claim(std::string s)
: val(std::move(s))
{}
explicit claim(const date& s)
: val(int64_t(std::chrono::system_clock::to_time_t(s)))
{}
explicit claim(const std::set<std::string>& s)
: val(picojson::array(s.cbegin(), s.cend()))
{}
explicit claim(const picojson::value& val)
: val(val)
{}
#else
claim(std::string s)
: val(std::move(s))
{}
claim(const date& s)
: val(int64_t(std::chrono::system_clock::to_time_t(s)))
{}
claim(const std::set<std::string>& s)
: val(picojson::array(s.cbegin(), s.cend()))
{}
claim(const picojson::value& val)
: val(val)
{}
#endif
/**
* Get wrapped json object
* \return Wrapped json object
*/
picojson::value to_json() const {
return val;
}
/**
* Get type of contained object
* \return Type
* \throws std::logic_error An internal error occured
*/
type get_type() const {
if (val.is<picojson::null>()) return type::null;
else if (val.is<bool>()) return type::boolean;
else if (val.is<int64_t>()) return type::int64;
else if (val.is<double>()) return type::number;
else if (val.is<std::string>()) return type::string;
else if (val.is<picojson::array>()) return type::array;
else if (val.is<picojson::object>()) return type::object;
else throw std::logic_error("internal error");
}
/**
* Get the contained object as a string
* \return content as string
* \throws std::bad_cast Content was not a string
*/
const std::string& as_string() const {
if (!val.is<std::string>())
throw std::bad_cast();
return val.get<std::string>();
}
/**
* Get the contained object as a date
* \return content as date
* \throws std::bad_cast Content was not a date
*/
date as_date() const {
return std::chrono::system_clock::from_time_t(as_int());
}
/**
* Get the contained object as an array
* \return content as array
* \throws std::bad_cast Content was not an array
*/
const picojson::array& as_array() const {
if (!val.is<picojson::array>())
throw std::bad_cast();
return val.get<picojson::array>();
}
/**
* Get the contained object as a set of strings
* \return content as set of strings
* \throws std::bad_cast Content was not a set
*/
const std::set<std::string> as_set() const {
std::set<std::string> res;
for(auto& e : as_array()) {
if(!e.is<std::string>())
throw std::bad_cast();
res.insert(e.get<std::string>());
}
return res;
}
/**
* Get the contained object as an integer
* \return content as int
* \throws std::bad_cast Content was not an int
*/
int64_t as_int() const {
if (!val.is<int64_t>())
throw std::bad_cast();
return val.get<int64_t>();
}
/**
* Get the contained object as a bool
* \return content as bool
* \throws std::bad_cast Content was not a bool
*/
bool as_bool() const {
if (!val.is<bool>())
throw std::bad_cast();
return val.get<bool>();
}
/**
* Get the contained object as a number
* \return content as double
* \throws std::bad_cast Content was not a number
*/
double as_number() const {
if (!val.is<double>())
throw std::bad_cast();
return val.get<double>();
}
};
/**
* Base class that represents a token payload.
* Contains Convenience accessors for common claims.
*/
class payload {
protected:
std::unordered_map<std::string, claim> payload_claims;
public:
/**
* Check if issuer is present ("iss")
* \return true if present, false otherwise
*/
bool has_issuer() const noexcept { return has_payload_claim("iss"); }
/**
* Check if subject is present ("sub")
* \return true if present, false otherwise
*/
bool has_subject() const noexcept { return has_payload_claim("sub"); }
/**
* Check if audience is present ("aud")
* \return true if present, false otherwise
*/
bool has_audience() const noexcept { return has_payload_claim("aud"); }
/**
* Check if expires is present ("exp")
* \return true if present, false otherwise
*/
bool has_expires_at() const noexcept { return has_payload_claim("exp"); }
/**
* Check if not before is present ("nbf")
* \return true if present, false otherwise
*/
bool has_not_before() const noexcept { return has_payload_claim("nbf"); }
/**
* Check if issued at is present ("iat")
* \return true if present, false otherwise
*/
bool has_issued_at() const noexcept { return has_payload_claim("iat"); }
/**
* Check if token id is present ("jti")
* \return true if present, false otherwise
*/
bool has_id() const noexcept { return has_payload_claim("jti"); }
/**
* Get issuer claim
* \return issuer as string
* \throws std::runtime_error If claim was not present
* \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token)
*/
const std::string& get_issuer() const { return get_payload_claim("iss").as_string(); }
/**
* Get subject claim
* \return subject as string
* \throws std::runtime_error If claim was not present
* \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token)
*/
const std::string& get_subject() const { return get_payload_claim("sub").as_string(); }
/**
* Get audience claim
* \return audience as a set of strings
* \throws std::runtime_error If claim was not present
* \throws std::bad_cast Claim was present but not a set (Should not happen in a valid token)
*/
std::set<std::string> get_audience() const {
auto aud = get_payload_claim("aud");
if(aud.get_type() == jwt::claim::type::string) return { aud.as_string()};
else return aud.as_set();
}
/**
* Get expires claim
* \return expires as a date in utc
* \throws std::runtime_error If claim was not present
* \throws std::bad_cast Claim was present but not a date (Should not happen in a valid token)
*/
const date get_expires_at() const { return get_payload_claim("exp").as_date(); }
/**
* Get not valid before claim
* \return nbf date in utc
* \throws std::runtime_error If claim was not present
* \throws std::bad_cast Claim was present but not a date (Should not happen in a valid token)
*/
const date get_not_before() const { return get_payload_claim("nbf").as_date(); }
/**
* Get issued at claim
* \return issued at as date in utc
* \throws std::runtime_error If claim was not present
* \throws std::bad_cast Claim was present but not a date (Should not happen in a valid token)
*/
const date get_issued_at() const { return get_payload_claim("iat").as_date(); }
/**
* Get id claim
* \return id as string
* \throws std::runtime_error If claim was not present
* \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token)
*/
const std::string& get_id() const { return get_payload_claim("jti").as_string(); }
/**
* Check if a payload claim is present
* \return true if claim was present, false otherwise
*/
bool has_payload_claim(const std::string& name) const noexcept { return payload_claims.count(name) != 0; }
/**
* Get payload claim
* \return Requested claim
* \throws std::runtime_error If claim was not present
*/
const claim& get_payload_claim(const std::string& name) const {
if (!has_payload_claim(name))
throw std::runtime_error("claim not found");
return payload_claims.at(name);
}
/**
* Get all payload claims
* \return map of claims
*/
std::unordered_map<std::string, claim> get_payload_claims() const { return payload_claims; }
};
/**
* Base class that represents a token header.
* Contains Convenience accessors for common claims.
*/
class header {
protected:
std::unordered_map<std::string, claim> header_claims;
public:
/**
* Check if algortihm is present ("alg")
* \return true if present, false otherwise
*/
bool has_algorithm() const noexcept { return has_header_claim("alg"); }
/**
* Check if type is present ("typ")
* \return true if present, false otherwise
*/
bool has_type() const noexcept { return has_header_claim("typ"); }
/**
* Check if content type is present ("cty")
* \return true if present, false otherwise
*/
bool has_content_type() const noexcept { return has_header_claim("cty"); }
/**
* Check if key id is present ("kid")
* \return true if present, false otherwise
*/
bool has_key_id() const noexcept { return has_header_claim("kid"); }
/**
* Get algorithm claim
* \return algorithm as string
* \throws std::runtime_error If claim was not present
* \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token)
*/
const std::string& get_algorithm() const { return get_header_claim("alg").as_string(); }
/**
* Get type claim
* \return type as a string
* \throws std::runtime_error If claim was not present
* \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token)
*/
const std::string& get_type() const { return get_header_claim("typ").as_string(); }
/**
* Get content type claim
* \return content type as string
* \throws std::runtime_error If claim was not present
* \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token)
*/
const std::string& get_content_type() const { return get_header_claim("cty").as_string(); }
/**
* Get key id claim
* \return key id as string
* \throws std::runtime_error If claim was not present
* \throws std::bad_cast Claim was present but not a string (Should not happen in a valid token)
*/
const std::string& get_key_id() const { return get_header_claim("kid").as_string(); }
/**
* Check if a header claim is present
* \return true if claim was present, false otherwise
*/
bool has_header_claim(const std::string& name) const noexcept { return header_claims.count(name) != 0; }
/**
* Get header claim
* \return Requested claim
* \throws std::runtime_error If claim was not present
*/
const claim& get_header_claim(const std::string& name) const {
if (!has_header_claim(name))
throw std::runtime_error("claim not found");
return header_claims.at(name);
}
/**
* Get all header claims
* \return map of claims
*/
std::unordered_map<std::string, claim> get_header_claims() const { return header_claims; }
};
/**
* Class containing all information about a decoded token
*/
class decoded_jwt : public header, public payload {
protected:
/// Unmodifed token, as passed to constructor
const std::string token;
/// Header part decoded from base64
std::string header;
/// Unmodified header part in base64
std::string header_base64;
/// Payload part decoded from base64
std::string payload;
/// Unmodified payload part in base64
std::string payload_base64;
/// Signature part decoded from base64
std::string signature;
/// Unmodified signature part in base64
std::string signature_base64;
public:
/**
* Constructor
* Parses a given token
* \param token The token to parse
* \throws std::invalid_argument Token is not in correct format
* \throws std::runtime_error Base64 decoding failed or invalid json
*/
explicit decoded_jwt(const std::string& token)
: token(token)
{
auto hdr_end = token.find('.');
if (hdr_end == std::string::npos)
throw std::invalid_argument("invalid token supplied");
auto payload_end = token.find('.', hdr_end + 1);
if (payload_end == std::string::npos)
throw std::invalid_argument("invalid token supplied");
header = header_base64 = token.substr(0, hdr_end);
payload = payload_base64 = token.substr(hdr_end + 1, payload_end - hdr_end - 1);
signature = signature_base64 = token.substr(payload_end + 1);
// Fix padding: JWT requires padding to get removed
auto fix_padding = [](std::string& str) {
switch (str.size() % 4) {
case 1:
str += alphabet::base64url::fill();
#ifdef __cpp_attributes
#if __has_cpp_attribute(fallthrough)
[[fallthrough]];
#endif
#endif
case 2:
str += alphabet::base64url::fill();
#ifdef __cpp_attributes
#if __has_cpp_attribute(fallthrough)
[[fallthrough]];
#endif
#endif
case 3:
str += alphabet::base64url::fill();
#ifdef __cpp_attributes
#if __has_cpp_attribute(fallthrough)
[[fallthrough]];
#endif
#endif
default:
break;
}
};
fix_padding(header);
fix_padding(payload);
fix_padding(signature);
header = base::decode<alphabet::base64url>(header);
payload = base::decode<alphabet::base64url>(payload);
signature = base::decode<alphabet::base64url>(signature);
auto parse_claims = [](const std::string& str) {
std::unordered_map<std::string, claim> res;
picojson::value val;
if (!picojson::parse(val, str).empty())
throw std::runtime_error("Invalid json");
for (auto& e : val.get<picojson::object>()) { res.insert({ e.first, claim(e.second) }); }
return res;
};
header_claims = parse_claims(header);
payload_claims = parse_claims(payload);
}
/**
* Get token string, as passed to constructor
* \return token as passed to constructor
*/
const std::string& get_token() const { return token; }
/**
* Get header part as json string
* \return header part after base64 decoding
*/
const std::string& get_header() const { return header; }
/**
* Get payload part as json string
* \return payload part after base64 decoding
*/
const std::string& get_payload() const { return payload; }
/**
* Get signature part as json string
* \return signature part after base64 decoding
*/
const std::string& get_signature() const { return signature; }
/**
* Get header part as base64 string
* \return header part before base64 decoding
*/
const std::string& get_header_base64() const { return header_base64; }
/**
* Get payload part as base64 string
* \return payload part before base64 decoding
*/
const std::string& get_payload_base64() const { return payload_base64; }
/**
* Get signature part as base64 string
* \return signature part before base64 decoding
*/
const std::string& get_signature_base64() const { return signature_base64; }
};
/**
* Builder class to build and sign a new token
* Use jwt::create() to get an instance of this class.
*/
class builder {
std::unordered_map<std::string, claim> header_claims;
std::unordered_map<std::string, claim> payload_claims;
builder() {}
friend builder create();
public:
/**
* Set a header claim.
* \param id Name of the claim
* \param c Claim to add
* \return *this to allow for method chaining
*/
builder& set_header_claim(const std::string& id, claim c) { header_claims[id] = std::move(c); return *this; }
/**
* Set a payload claim.
* \param id Name of the claim
* \param c Claim to add
* \return *this to allow for method chaining
*/
builder& set_payload_claim(const std::string& id, claim c) { payload_claims[id] = std::move(c); return *this; }
/**
* Set algorithm claim
* You normally don't need to do this, as the algorithm is automatically set if you don't change it.
* \param str Name of algorithm
* \return *this to allow for method chaining
*/
builder& set_algorithm(const std::string& str) { return set_header_claim("alg", claim(str)); }
/**
* Set type claim
* \param str Type to set
* \return *this to allow for method chaining
*/
builder& set_type(const std::string& str) { return set_header_claim("typ", claim(str)); }
/**
* Set content type claim
* \param str Type to set
* \return *this to allow for method chaining
*/
builder& set_content_type(const std::string& str) { return set_header_claim("cty", claim(str)); }
/**
* Set key id claim
* \param str Key id to set
* \return *this to allow for method chaining
*/
builder& set_key_id(const std::string& str) { return set_header_claim("kid", claim(str)); }
/**
* Set issuer claim
* \param str Issuer to set
* \return *this to allow for method chaining
*/
builder& set_issuer(const std::string& str) { return set_payload_claim("iss", claim(str)); }
/**
* Set subject claim
* \param str Subject to set
* \return *this to allow for method chaining
*/
builder& set_subject(const std::string& str) { return set_payload_claim("sub", claim(str)); }
/**
* Set audience claim
* \param l Audience set
* \return *this to allow for method chaining
*/
builder& set_audience(const std::set<std::string>& l) { return set_payload_claim("aud", claim(l)); }
/**
* Set audience claim
* \param aud Single audience
* \return *this to allow for method chaining
*/
builder& set_audience(const std::string& aud) { return set_payload_claim("aud", claim(aud)); }
/**
* Set expires at claim
* \param d Expires time
* \return *this to allow for method chaining
*/
builder& set_expires_at(const date& d) { return set_payload_claim("exp", claim(d)); }
/**
* Set not before claim
* \param d First valid time
* \return *this to allow for method chaining
*/
builder& set_not_before(const date& d) { return set_payload_claim("nbf", claim(d)); }
/**
* Set issued at claim
* \param d Issued at time, should be current time
* \return *this to allow for method chaining
*/
builder& set_issued_at(const date& d) { return set_payload_claim("iat", claim(d)); }
/**
* Set id claim
* \param str ID to set
* \return *this to allow for method chaining
*/
builder& set_id(const std::string& str) { return set_payload_claim("jti", claim(str)); }
/**
* Sign token and return result
* \param algo Instance of an algorithm to sign the token with
* \return Final token as a string
*/
template<typename T>
std::string sign(const T& algo) {
this->set_algorithm(algo.name());
picojson::object obj_header;
for (auto& e : header_claims) {
obj_header.insert({ e.first, e.second.to_json() });
}
picojson::object obj_payload;
for (auto& e : payload_claims) {
obj_payload.insert({ e.first, e.second.to_json() });
}
auto encode = [](const std::string& data) {
auto base = base::encode<alphabet::base64url>(data);
auto pos = base.find(alphabet::base64url::fill());
base = base.substr(0, pos);
return base;
};
std::string header = encode(picojson::value(obj_header).serialize());
std::string payload = encode(picojson::value(obj_payload).serialize());
std::string token = header + "." + payload;
return token + "." + encode(algo.sign(token));
}
};
/**
* Verifier class used to check if a decoded token contains all claims required by your application and has a valid signature.
*/
template<typename Clock>
class verifier {
struct algo_base {
virtual ~algo_base() = default;
virtual void verify(const std::string& data, const std::string& sig) = 0;
};
template<typename T>
struct algo : public algo_base {
T alg;
explicit algo(T a) : alg(a) {}
virtual void verify(const std::string& data, const std::string& sig) override {
alg.verify(data, sig);
}
};
/// Required claims
std::unordered_map<std::string, claim> claims;
/// Leeway time for exp, nbf and iat
size_t default_leeway = 0;
/// Instance of clock type
Clock clock;
/// Supported algorithms
std::unordered_map<std::string, std::shared_ptr<algo_base>> algs;
public:
/**
* Constructor for building a new verifier instance
* \param c Clock instance
*/
explicit verifier(Clock c) : clock(c) {}
/**
* Set default leeway to use.
* \param leeway Default leeway to use if not specified otherwise
* \return *this to allow chaining
*/
verifier& leeway(size_t leeway) { default_leeway = leeway; return *this; }
/**
* Set leeway for expires at.
* If not specified the default leeway will be used.
* \param leeway Set leeway to use for expires at.
* \return *this to allow chaining
*/
verifier& expires_at_leeway(size_t leeway) { return with_claim("exp", claim(std::chrono::system_clock::from_time_t(leeway))); }
/**
* Set leeway for not before.
* If not specified the default leeway will be used.
* \param leeway Set leeway to use for not before.
* \return *this to allow chaining
*/
verifier& not_before_leeway(size_t leeway) { return with_claim("nbf", claim(std::chrono::system_clock::from_time_t(leeway))); }
/**
* Set leeway for issued at.
* If not specified the default leeway will be used.
* \param leeway Set leeway to use for issued at.
* \return *this to allow chaining
*/
verifier& issued_at_leeway(size_t leeway) { return with_claim("iat", claim(std::chrono::system_clock::from_time_t(leeway))); }
/**
* Set an issuer to check for.
* Check is casesensitive.
* \param iss Issuer to check for.
* \return *this to allow chaining
*/
verifier& with_issuer(const std::string& iss) { return with_claim("iss", claim(iss)); }
/**
* Set a subject to check for.
* Check is casesensitive.
* \param sub Subject to check for.
* \return *this to allow chaining
*/
verifier& with_subject(const std::string& sub) { return with_claim("sub", claim(sub)); }
/**
* Set an audience to check for.
* If any of the specified audiences is not present in the token the check fails.
* \param aud Audience to check for.
* \return *this to allow chaining
*/
verifier& with_audience(const std::set<std::string>& aud) { return with_claim("aud", claim(aud)); }
/**
* Set an id to check for.
* Check is casesensitive.
* \param id ID to check for.
* \return *this to allow chaining
*/
verifier& with_id(const std::string& id) { return with_claim("jti", claim(id)); }
/**
* Specify a claim to check for.
* \param name Name of the claim to check for
* \param c Claim to check for
* \return *this to allow chaining
*/
verifier& with_claim(const std::string& name, claim c) { claims[name] = c; return *this; }
/**
* Add an algorithm available for checking.
* \param alg Algorithm to allow
* \return *this to allow chaining
*/
template<typename Algorithm>
verifier& allow_algorithm(Algorithm alg) {
algs[alg.name()] = std::make_shared<algo<Algorithm>>(alg);
return *this;
}
/**
* Verify the given token.
* \param jwt Token to check
* \throws token_verification_exception Verification failed
*/
void verify(const decoded_jwt& jwt) const {
const std::string data = jwt.get_header_base64() + "." + jwt.get_payload_base64();
const std::string sig = jwt.get_signature();
const std::string& algo = jwt.get_algorithm();
if (algs.count(algo) == 0)
throw token_verification_exception("wrong algorithm");
algs.at(algo)->verify(data, sig);
auto assert_claim_eq = [](const decoded_jwt& jwt, const std::string& key, const claim& c) {
if (!jwt.has_payload_claim(key))
throw token_verification_exception("decoded_jwt is missing " + key + " claim");
auto& jc = jwt.get_payload_claim(key);
if (jc.get_type() != c.get_type())
throw token_verification_exception("claim " + key + " type mismatch");
if (c.get_type() == claim::type::int64) {
if (c.as_date() != jc.as_date())
throw token_verification_exception("claim " + key + " does not match expected");
}
else if (c.get_type() == claim::type::array) {
auto s1 = c.as_set();
auto s2 = jc.as_set();
if (s1.size() != s2.size())
throw token_verification_exception("claim " + key + " does not match expected");
auto it1 = s1.cbegin();
auto it2 = s2.cbegin();
while (it1 != s1.cend() && it2 != s2.cend()) {
if (*it1++ != *it2++)
throw token_verification_exception("claim " + key + " does not match expected");
}
}
else if (c.get_type() == claim::type::string) {
if (c.as_string() != jc.as_string())
throw token_verification_exception("claim " + key + " does not match expected");
}
else throw token_verification_exception("internal error");
};
auto time = clock.now();
if (jwt.has_expires_at()) {
auto leeway = claims.count("exp") == 1 ? std::chrono::system_clock::to_time_t(claims.at("exp").as_date()) : default_leeway;
auto exp = jwt.get_expires_at();
if (time > exp + std::chrono::seconds(leeway))
throw token_verification_exception("token expired");
}
if (jwt.has_issued_at()) {
auto leeway = claims.count("iat") == 1 ? std::chrono::system_clock::to_time_t(claims.at("iat").as_date()) : default_leeway;
auto iat = jwt.get_issued_at();
if (time < iat - std::chrono::seconds(leeway))
throw token_verification_exception("token expired");
}
if (jwt.has_not_before()) {
auto leeway = claims.count("nbf") == 1 ? std::chrono::system_clock::to_time_t(claims.at("nbf").as_date()) : default_leeway;
auto nbf = jwt.get_not_before();
if (time < nbf - std::chrono::seconds(leeway))
throw token_verification_exception("token expired");
}
for (auto& c : claims)
{
if (c.first == "exp" || c.first == "iat" || c.first == "nbf") {
// Nothing to do here, already checked
}
else if (c.first == "aud") {
if (!jwt.has_audience())
throw token_verification_exception("token doesn't contain the required audience");
auto aud = jwt.get_audience();
auto expected = c.second.as_set();
for (auto& e : expected)
if (aud.count(e) == 0)
throw token_verification_exception("token doesn't contain the required audience");
}
else {
assert_claim_eq(jwt, c.first, c.second);
}
}
}
};
/**
* Create a verifier using the given clock
* \param c Clock instance to use
* \return verifier instance
*/
template<typename Clock>
verifier<Clock> verify(Clock c) {
return verifier<Clock>(c);
}
/**
* Default clock class using std::chrono::system_clock as a backend.
*/
struct default_clock {
std::chrono::system_clock::time_point now() const {
return std::chrono::system_clock::now();
}
};
/**
* Create a verifier using the default clock
* \return verifier instance
*/
inline
verifier<default_clock> verify() {
return verify<default_clock>({});
}
/**
* Return a builder instance to create a new token
*/
inline
builder create() {
return builder();
}
/**
* Decode a token
* \param token Token to decode
* \return Decoded token
* \throws std::invalid_argument Token is not in correct format
* \throws std::runtime_error Base64 decoding failed or invalid json
*/
inline
decoded_jwt decode(const std::string& token) {
return decoded_jwt(token);
}
}
|