-
-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathjwt.h
3039 lines (2835 loc) · 110 KB
/
jwt.h
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
#ifndef JWT_CPP_JWT_H
#define JWT_CPP_JWT_H
#ifndef JWT_DISABLE_PICOJSON
#ifndef PICOJSON_USE_INT64
#define PICOJSON_USE_INT64
#endif
#include "picojson/picojson.h"
#endif
#ifndef JWT_DISABLE_BASE64
#include "base.h"
#endif
#include <openssl/ec.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/pem.h>
#include <algorithm>
#include <chrono>
#include <memory>
#include <set>
#include <system_error>
#include <type_traits>
#include <unordered_map>
#include <utility>
#if __cplusplus >= 201402L
#ifdef __has_include
#if __has_include(<experimental/type_traits>)
#include <experimental/type_traits>
#endif
#endif
#endif
// If openssl version less than 1.1
#if OPENSSL_VERSION_NUMBER < 0x10100000L
#define OPENSSL10
#endif
// If openssl version less than 1.1.1
#if OPENSSL_VERSION_NUMBER < 0x10101000L
#define OPENSSL110
#endif
#if defined(LIBRESSL_VERSION_NUMBER)
#define OPENSSL10
#define OPENSSL110
#endif
#ifndef JWT_CLAIM_EXPLICIT
#define JWT_CLAIM_EXPLICIT explicit
#endif
/**
* \brief JSON Web Token
*
* A namespace to contain everything related to handling JSON Web Tokens, JWT for short,
* as a part of [RFC7519](https://tools.ietf.org/html/rfc7519), or alternatively for
* JWS (JSON Web Signature) from [RFC7515](https://tools.ietf.org/html/rfc7515)
*/
namespace jwt {
using date = std::chrono::system_clock::time_point;
/**
* \brief Everything related to error codes issued by the library
*/
namespace error {
struct signature_verification_exception : public std::system_error {
using system_error::system_error;
};
struct signature_generation_exception : public std::system_error {
using system_error::system_error;
};
struct rsa_exception : public std::system_error {
using system_error::system_error;
};
struct ecdsa_exception : public std::system_error {
using system_error::system_error;
};
struct token_verification_exception : public std::system_error {
using system_error::system_error;
};
/**
* \brief Errors related to processing of RSA signatures
*/
enum class rsa_error {
ok = 0,
cert_load_failed = 10,
get_key_failed,
write_key_failed,
write_cert_failed,
convert_to_pem_failed,
load_key_bio_write,
load_key_bio_read,
create_mem_bio_failed,
no_key_provided
};
/**
* \brief Error category for RSA errors
*/
inline std::error_category& rsa_error_category() {
class rsa_error_cat : public std::error_category {
public:
const char* name() const noexcept override { return "rsa_error"; };
std::string message(int ev) const override {
switch (static_cast<rsa_error>(ev)) {
case rsa_error::ok: return "no error";
case rsa_error::cert_load_failed: return "error loading cert into memory";
case rsa_error::get_key_failed: return "error getting key from certificate";
case rsa_error::write_key_failed: return "error writing key data in PEM format";
case rsa_error::write_cert_failed: return "error writing cert data in PEM format";
case rsa_error::convert_to_pem_failed: return "failed to convert key to pem";
case rsa_error::load_key_bio_write: return "failed to load key: bio write failed";
case rsa_error::load_key_bio_read: return "failed to load key: bio read failed";
case rsa_error::create_mem_bio_failed: return "failed to create memory bio";
case rsa_error::no_key_provided: return "at least one of public or private key need to be present";
default: return "unknown RSA error";
}
}
};
static rsa_error_cat cat;
return cat;
}
inline std::error_code make_error_code(rsa_error e) { return {static_cast<int>(e), rsa_error_category()}; }
/**
* \brief Errors related to processing of RSA signatures
*/
enum class ecdsa_error {
ok = 0,
load_key_bio_write = 10,
load_key_bio_read,
create_mem_bio_failed,
no_key_provided,
invalid_key_size,
invalid_key
};
/**
* \brief Error category for ECDSA errors
*/
inline std::error_category& ecdsa_error_category() {
class ecdsa_error_cat : public std::error_category {
public:
const char* name() const noexcept override { return "ecdsa_error"; };
std::string message(int ev) const override {
switch (static_cast<ecdsa_error>(ev)) {
case ecdsa_error::ok: return "no error";
case ecdsa_error::load_key_bio_write: return "failed to load key: bio write failed";
case ecdsa_error::load_key_bio_read: return "failed to load key: bio read failed";
case ecdsa_error::create_mem_bio_failed: return "failed to create memory bio";
case ecdsa_error::no_key_provided:
return "at least one of public or private key need to be present";
case ecdsa_error::invalid_key_size: return "invalid key size";
case ecdsa_error::invalid_key: return "invalid key";
default: return "unknown ECDSA error";
}
}
};
static ecdsa_error_cat cat;
return cat;
}
inline std::error_code make_error_code(ecdsa_error e) { return {static_cast<int>(e), ecdsa_error_category()}; }
/**
* \brief Errors related to verification of signatures
*/
enum class signature_verification_error {
ok = 0,
invalid_signature = 10,
create_context_failed,
verifyinit_failed,
verifyupdate_failed,
verifyfinal_failed,
get_key_failed
};
/**
* \brief Error category for verification errors
*/
inline std::error_category& signature_verification_error_category() {
class verification_error_cat : public std::error_category {
public:
const char* name() const noexcept override { return "signature_verification_error"; };
std::string message(int ev) const override {
switch (static_cast<signature_verification_error>(ev)) {
case signature_verification_error::ok: return "no error";
case signature_verification_error::invalid_signature: return "invalid signature";
case signature_verification_error::create_context_failed:
return "failed to verify signature: could not create context";
case signature_verification_error::verifyinit_failed:
return "failed to verify signature: VerifyInit failed";
case signature_verification_error::verifyupdate_failed:
return "failed to verify signature: VerifyUpdate failed";
case signature_verification_error::verifyfinal_failed:
return "failed to verify signature: VerifyFinal failed";
case signature_verification_error::get_key_failed:
return "failed to verify signature: Could not get key";
default: return "unknown signature verification error";
}
}
};
static verification_error_cat cat;
return cat;
}
inline std::error_code make_error_code(signature_verification_error e) {
return {static_cast<int>(e), signature_verification_error_category()};
}
/**
* \brief Errors related to signature generation errors
*/
enum class signature_generation_error {
ok = 0,
hmac_failed = 10,
create_context_failed,
signinit_failed,
signupdate_failed,
signfinal_failed,
ecdsa_do_sign_failed,
digestinit_failed,
digestupdate_failed,
digestfinal_failed,
rsa_padding_failed,
rsa_private_encrypt_failed,
get_key_failed
};
/**
* \brief Error category for signature generation errors
*/
inline std::error_category& signature_generation_error_category() {
class signature_generation_error_cat : public std::error_category {
public:
const char* name() const noexcept override { return "signature_generation_error"; };
std::string message(int ev) const override {
switch (static_cast<signature_generation_error>(ev)) {
case signature_generation_error::ok: return "no error";
case signature_generation_error::hmac_failed: return "hmac failed";
case signature_generation_error::create_context_failed:
return "failed to create signature: could not create context";
case signature_generation_error::signinit_failed:
return "failed to create signature: SignInit failed";
case signature_generation_error::signupdate_failed:
return "failed to create signature: SignUpdate failed";
case signature_generation_error::signfinal_failed:
return "failed to create signature: SignFinal failed";
case signature_generation_error::ecdsa_do_sign_failed: return "failed to generate ecdsa signature";
case signature_generation_error::digestinit_failed:
return "failed to create signature: DigestInit failed";
case signature_generation_error::digestupdate_failed:
return "failed to create signature: DigestUpdate failed";
case signature_generation_error::digestfinal_failed:
return "failed to create signature: DigestFinal failed";
case signature_generation_error::rsa_padding_failed:
return "failed to create signature: RSA_padding_add_PKCS1_PSS_mgf1 failed";
case signature_generation_error::rsa_private_encrypt_failed:
return "failed to create signature: RSA_private_encrypt failed";
case signature_generation_error::get_key_failed:
return "failed to generate signature: Could not get key";
default: return "unknown signature generation error";
}
}
};
static signature_generation_error_cat cat = {};
return cat;
}
inline std::error_code make_error_code(signature_generation_error e) {
return {static_cast<int>(e), signature_generation_error_category()};
}
/**
* \brief Errors related to token verification errors
*/
enum class token_verification_error {
ok = 0,
wrong_algorithm = 10,
missing_claim,
claim_type_missmatch,
claim_value_missmatch,
token_expired,
audience_missmatch
};
/**
* \brief Error category for token verification errors
*/
inline std::error_category& token_verification_error_category() {
class token_verification_error_cat : public std::error_category {
public:
const char* name() const noexcept override { return "token_verification_error"; };
std::string message(int ev) const override {
switch (static_cast<token_verification_error>(ev)) {
case token_verification_error::ok: return "no error";
case token_verification_error::wrong_algorithm: return "wrong algorithm";
case token_verification_error::missing_claim: return "decoded JWT is missing required claim(s)";
case token_verification_error::claim_type_missmatch:
return "claim type does not match expected type";
case token_verification_error::claim_value_missmatch:
return "claim value does not match expected value";
case token_verification_error::token_expired: return "token expired";
case token_verification_error::audience_missmatch:
return "token doesn't contain the required audience";
default: return "unknown token verification error";
}
}
};
static token_verification_error_cat cat = {};
return cat;
}
inline std::error_code make_error_code(token_verification_error e) {
return {static_cast<int>(e), token_verification_error_category()};
}
inline void throw_if_error(std::error_code ec) {
if (ec) {
if (ec.category() == rsa_error_category()) throw rsa_exception(ec);
if (ec.category() == ecdsa_error_category()) throw ecdsa_exception(ec);
if (ec.category() == signature_verification_error_category())
throw signature_verification_exception(ec);
if (ec.category() == signature_generation_error_category()) throw signature_generation_exception(ec);
if (ec.category() == token_verification_error_category()) throw token_verification_exception(ec);
}
}
} // namespace error
// FIXME: Remove
// Keep backward compat at least for a couple of revisions
using error::ecdsa_exception;
using error::rsa_exception;
using error::signature_generation_exception;
using error::signature_verification_exception;
using error::token_verification_exception;
} // namespace jwt
namespace std {
template<>
struct is_error_code_enum<jwt::error::rsa_error> : true_type {};
template<>
struct is_error_code_enum<jwt::error::ecdsa_error> : true_type {};
template<>
struct is_error_code_enum<jwt::error::signature_verification_error> : true_type {};
template<>
struct is_error_code_enum<jwt::error::signature_generation_error> : true_type {};
template<>
struct is_error_code_enum<jwt::error::token_verification_error> : true_type {};
} // namespace std
namespace jwt {
/**
* \brief A collection for working with certificates
*
* These _helpers_ are usefully when working with certificates OpenSSL APIs.
* For example, when dealing with JWKS (JSON Web Key Set)[https://tools.ietf.org/html/rfc7517]
* you maybe need to extract the modulus and exponent of an RSA Public Key.
*/
namespace helper {
/**
* \brief Extract the public key of a pem certificate
*
* \param certstr String containing the certificate encoded as pem
* \param pw Password used to decrypt certificate (leave empty if not encrypted)
* \param ec error_code for error_detection (gets cleared if no error occures)
*/
inline std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw,
std::error_code& ec) {
ec.clear();
#if OPENSSL_VERSION_NUMBER <= 0x10100003L
std::unique_ptr<BIO, decltype(&BIO_free_all)> certbio(
BIO_new_mem_buf(const_cast<char*>(certstr.data()), static_cast<int>(certstr.size())), BIO_free_all);
#else
std::unique_ptr<BIO, decltype(&BIO_free_all)> certbio(
BIO_new_mem_buf(certstr.data(), static_cast<int>(certstr.size())), BIO_free_all);
#endif
std::unique_ptr<BIO, decltype(&BIO_free_all)> keybio(BIO_new(BIO_s_mem()), BIO_free_all);
if (!certbio || !keybio) {
ec = error::rsa_error::create_mem_bio_failed;
return {};
}
std::unique_ptr<X509, decltype(&X509_free)> cert(
PEM_read_bio_X509(certbio.get(), nullptr, nullptr, const_cast<char*>(pw.c_str())), X509_free);
if (!cert) {
ec = error::rsa_error::cert_load_failed;
return {};
}
std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> key(X509_get_pubkey(cert.get()), EVP_PKEY_free);
if (!key) {
ec = error::rsa_error::get_key_failed;
return {};
}
if (PEM_write_bio_PUBKEY(keybio.get(), key.get()) == 0) {
ec = error::rsa_error::write_key_failed;
return {};
}
char* ptr = nullptr;
auto len = BIO_get_mem_data(keybio.get(), &ptr);
if (len <= 0 || ptr == nullptr) {
ec = error::rsa_error::convert_to_pem_failed;
return {};
}
return {ptr, static_cast<size_t>(len)};
}
/**
* \brief Extract the public key of a pem certificate
*
* \param certstr String containing the certificate encoded as pem
* \param pw Password used to decrypt certificate (leave empty if not encrypted)
* \throw rsa_exception if an error occurred
*/
inline std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw = "") {
std::error_code ec;
auto res = extract_pubkey_from_cert(certstr, pw, ec);
error::throw_if_error(ec);
return res;
}
/**
* \brief Convert the certificate provided as base64 DER to PEM.
*
* This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
* (here)[https://tools.ietf.org/html/rfc7517#section-4.7]
*
* \tparam Decode is callabled, taking a string_type and returns a string_type.
* It should ensure the padding of the input and then base64 decode and return
* the results.
*
* \param cert_base64_der_str String containing the certificate encoded as base64 DER
* \param decode The function to decode the cert
* \param ec error_code for error_detection (gets cleared if no error occures)
*/
template<typename Decode>
std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, Decode decode,
std::error_code& ec) {
ec.clear();
const auto decodedStr = decode(cert_base64_der_str);
auto c_str = reinterpret_cast<const unsigned char*>(decodedStr.c_str());
std::unique_ptr<X509, decltype(&X509_free)> cert(d2i_X509(NULL, &c_str, decodedStr.size()), X509_free);
std::unique_ptr<BIO, decltype(&BIO_free_all)> certbio(BIO_new(BIO_s_mem()), BIO_free_all);
if (!cert || !certbio) {
ec = error::rsa_error::create_mem_bio_failed;
return {};
}
if (!PEM_write_bio_X509(certbio.get(), cert.get())) {
ec = error::rsa_error::write_cert_failed;
return {};
}
char* ptr = nullptr;
const auto len = BIO_get_mem_data(certbio.get(), &ptr);
if (len <= 0 || ptr == nullptr) {
ec = error::rsa_error::convert_to_pem_failed;
return {};
}
return {ptr, static_cast<size_t>(len)};
}
/**
* \brief Convert the certificate provided as base64 DER to PEM.
*
* This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
* (here)[https://tools.ietf.org/html/rfc7517#section-4.7]
*
* \tparam Decode is callabled, taking a string_type and returns a string_type.
* It should ensure the padding of the input and then base64 decode and return
* the results.
*
* \param cert_base64_der_str String containing the certificate encoded as base64 DER
* \param decode The function to decode the cert
* \throw rsa_exception if an error occurred
*/
template<typename Decode>
std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, Decode decode) {
std::error_code ec;
auto res = convert_base64_der_to_pem(cert_base64_der_str, std::move(decode), ec);
error::throw_if_error(ec);
return res;
}
#ifndef JWT_DISABLE_BASE64
/**
* \brief Convert the certificate provided as base64 DER to PEM.
*
* This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
* (here)[https://tools.ietf.org/html/rfc7517#section-4.7]
*
* \param cert_base64_der_str String containing the certificate encoded as base64 DER
* \param ec error_code for error_detection (gets cleared if no error occures)
*/
inline std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, std::error_code& ec) {
auto decode = [](const std::string& token) {
return base::decode<alphabet::base64>(base::pad<alphabet::base64>(token));
};
return convert_base64_der_to_pem(cert_base64_der_str, std::move(decode), ec);
}
/**
* \brief Convert the certificate provided as base64 DER to PEM.
*
* This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info
* (here)[https://tools.ietf.org/html/rfc7517#section-4.7]
*
* \param cert_base64_der_str String containing the certificate encoded as base64 DER
* \throw rsa_exception if an error occurred
*/
inline std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str) {
std::error_code ec;
auto res = convert_base64_der_to_pem(cert_base64_der_str, ec);
error::throw_if_error(ec);
return res;
}
#endif
/**
* \brief Load a public key from a string.
*
* The string should contain a pem encoded certificate or public key
*
* \param certstr String containing the certificate encoded as pem
* \param pw Password used to decrypt certificate (leave empty if not encrypted)
* \param ec error_code for error_detection (gets cleared if no error occures)
*/
inline std::shared_ptr<EVP_PKEY> load_public_key_from_string(const std::string& key,
const std::string& password, std::error_code& ec) {
ec.clear();
std::unique_ptr<BIO, decltype(&BIO_free_all)> pubkey_bio(BIO_new(BIO_s_mem()), BIO_free_all);
if (!pubkey_bio) {
ec = error::rsa_error::create_mem_bio_failed;
return nullptr;
}
if (key.substr(0, 27) == "-----BEGIN CERTIFICATE-----") {
auto epkey = helper::extract_pubkey_from_cert(key, password, ec);
if (ec) return nullptr;
const int len = static_cast<int>(epkey.size());
if (BIO_write(pubkey_bio.get(), epkey.data(), len) != len) {
ec = error::rsa_error::load_key_bio_write;
return nullptr;
}
} else {
const int len = static_cast<int>(key.size());
if (BIO_write(pubkey_bio.get(), key.data(), len) != len) {
ec = error::rsa_error::load_key_bio_write;
return nullptr;
}
}
std::shared_ptr<EVP_PKEY> pkey(
PEM_read_bio_PUBKEY(pubkey_bio.get(), nullptr, nullptr,
(void*)password.data()), // NOLINT(google-readability-casting) requires `const_cast`
EVP_PKEY_free);
if (!pkey) {
ec = error::rsa_error::load_key_bio_read;
return nullptr;
}
return pkey;
}
/**
* \brief Load a public key from a string.
*
* The string should contain a pem encoded certificate or public key
*
* \param certstr String containing the certificate or key encoded as pem
* \param pw Password used to decrypt certificate or key (leave empty if not encrypted)
* \throw rsa_exception if an error occurred
*/
inline std::shared_ptr<EVP_PKEY> load_public_key_from_string(const std::string& key,
const std::string& password = "") {
std::error_code ec;
auto res = load_public_key_from_string(key, password, ec);
error::throw_if_error(ec);
return res;
}
/**
* \brief Load a private key from a string.
*
* \param key String containing a private key as pem
* \param pw Password used to decrypt key (leave empty if not encrypted)
* \param ec error_code for error_detection (gets cleared if no error occures)
*/
inline std::shared_ptr<EVP_PKEY>
load_private_key_from_string(const std::string& key, const std::string& password, std::error_code& ec) {
std::unique_ptr<BIO, decltype(&BIO_free_all)> privkey_bio(BIO_new(BIO_s_mem()), BIO_free_all);
if (!privkey_bio) {
ec = error::rsa_error::create_mem_bio_failed;
return nullptr;
}
const int len = static_cast<int>(key.size());
if (BIO_write(privkey_bio.get(), key.data(), len) != len) {
ec = error::rsa_error::load_key_bio_write;
return nullptr;
}
std::shared_ptr<EVP_PKEY> pkey(
PEM_read_bio_PrivateKey(privkey_bio.get(), nullptr, nullptr, const_cast<char*>(password.c_str())),
EVP_PKEY_free);
if (!pkey) {
ec = error::rsa_error::load_key_bio_read;
return nullptr;
}
return pkey;
}
/**
* \brief Load a private key from a string.
*
* \param key String containing a private key as pem
* \param pw Password used to decrypt key (leave empty if not encrypted)
* \throw rsa_exception if an error occurred
*/
inline std::shared_ptr<EVP_PKEY> load_private_key_from_string(const std::string& key,
const std::string& password = "") {
std::error_code ec;
auto res = load_private_key_from_string(key, password, ec);
error::throw_if_error(ec);
return res;
}
/**
* Convert a OpenSSL BIGNUM to a std::string
* \param bn BIGNUM to convert
* \return bignum as string
*/
inline
#ifdef OPENSSL10
static std::string
bn2raw(BIGNUM* bn)
#else
static std::string
bn2raw(const BIGNUM* bn)
#endif
{
std::string res(BN_num_bytes(bn), '\0');
BN_bn2bin(bn, (unsigned char*)res.data()); // NOLINT(google-readability-casting) requires `const_cast`
return res;
}
/**
* Convert an std::string to a OpenSSL BIGNUM
* \param raw String to convert
* \return BIGNUM representation
*/
inline static std::unique_ptr<BIGNUM, decltype(&BN_free)> raw2bn(const std::string& raw) {
return std::unique_ptr<BIGNUM, decltype(&BN_free)>(
BN_bin2bn(reinterpret_cast<const unsigned char*>(raw.data()), static_cast<int>(raw.size()), nullptr),
BN_free);
}
} // namespace helper
/**
* \brief Various cryptographic algorithms when working with JWT
*
* JWT (JSON Web Tokens) signatures are typically used as the payload for a JWS (JSON Web Signature) or
* JWE (JSON Web Encryption). Both of these use various cryptographic as specified by
* [RFC7518](https://tools.ietf.org/html/rfc7518) and are exposed through the a [JOSE
* Header](https://tools.ietf.org/html/rfc7515#section-4) which points to one of the JWA (JSON Web
* Algorithms)(https://tools.ietf.org/html/rfc7518#section-3.1)
*/
namespace algorithm {
/**
* \brief "none" algorithm.
*
* Returns and empty signature and checks if the given signature is empty.
*/
struct none {
/**
* \brief Return an empty string
*/
std::string sign(const std::string& /*unused*/, std::error_code& ec) const {
ec.clear();
return {};
}
/**
* \brief Check if the given signature is empty.
*
* JWT's with "none" algorithm should not contain a signature.
* \param signature Signature data to verify
* \param ec error_code filled with details about the error
*/
void verify(const std::string& /*unused*/, const std::string& signature, std::error_code& ec) const {
ec.clear();
if (!signature.empty()) { ec = error::signature_verification_error::invalid_signature; }
}
/// Get algorithm name
std::string name() const { return "none"; }
};
/**
* \brief 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)(), std::string name)
: secret(std::move(key)), md(md), alg_name(std::move(name)) {}
/**
* Sign jwt data
* \param data The data to sign
* \param ec error_code filled with details on error
* \return HMAC signature for the given data
*/
std::string sign(const std::string& data, std::error_code& ec) const {
ec.clear();
std::string res(static_cast<size_t>(EVP_MAX_MD_SIZE), '\0');
auto len = static_cast<unsigned int>(res.size());
if (HMAC(md(), secret.data(), static_cast<int>(secret.size()),
reinterpret_cast<const unsigned char*>(data.data()), static_cast<int>(data.size()),
(unsigned char*)res.data(), // NOLINT(google-readability-casting) requires `const_cast`
&len) == nullptr) {
ec = error::signature_generation_error::hmac_failed;
return {};
}
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
* \param ec Filled with details about failure.
*/
void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
ec.clear();
auto res = sign(data, ec);
if (ec) return;
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) {
ec = error::signature_verification_error::invalid_signature;
return;
}
}
/**
* Returns the algorithm name provided to the constructor
* \return algorithm's name
*/
std::string name() const { return alg_name; }
private:
/// HMAC secrect
const std::string secret;
/// HMAC hash generator
const EVP_MD* (*md)();
/// algorithm's name
const std::string alg_name;
};
/**
* \brief 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 private_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)(), std::string name)
: md(md), alg_name(std::move(name)) {
if (!private_key.empty()) {
pkey = helper::load_private_key_from_string(private_key, private_key_password);
} else if (!public_key.empty()) {
pkey = helper::load_public_key_from_string(public_key, public_key_password);
} else
throw rsa_exception(error::rsa_error::no_key_provided);
}
/**
* Sign jwt data
* \param data The data to sign
* \param ec error_code filled with details on error
* \return RSA signature for the given data
*/
std::string sign(const std::string& data, std::error_code& ec) const {
ec.clear();
#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) {
ec = error::signature_generation_error::create_context_failed;
return {};
}
if (!EVP_SignInit(ctx.get(), md())) {
ec = error::signature_generation_error::signinit_failed;
return {};
}
std::string res(EVP_PKEY_size(pkey.get()), '\0');
unsigned int len = 0;
if (!EVP_SignUpdate(ctx.get(), data.data(), data.size())) {
ec = error::signature_generation_error::signupdate_failed;
return {};
}
if (EVP_SignFinal(ctx.get(), (unsigned char*)res.data(), &len, pkey.get()) == 0) {
ec = error::signature_generation_error::signfinal_failed;
return {};
}
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
* \param ec Filled with details on failure
*/
void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
ec.clear();
#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) {
ec = error::signature_verification_error::create_context_failed;
return;
}
if (!EVP_VerifyInit(ctx.get(), md())) {
ec = error::signature_verification_error::verifyinit_failed;
return;
}
if (!EVP_VerifyUpdate(ctx.get(), data.data(), data.size())) {
ec = error::signature_verification_error::verifyupdate_failed;
return;
}
auto res = EVP_VerifyFinal(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
static_cast<unsigned int>(signature.size()), pkey.get());
if (res != 1) {
ec = error::signature_verification_error::verifyfinal_failed;
return;
}
}
/**
* Returns the algorithm name provided to the constructor
* \return algorithm's name
*/
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)();
/// algorithm's name
const std::string alg_name;
};
/**
* \brief 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 private_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)(), std::string name, size_t siglen)
: md(md), alg_name(std::move(name)), signature_length(siglen) {
if (!public_key.empty()) {
std::unique_ptr<BIO, decltype(&BIO_free_all)> pubkey_bio(BIO_new(BIO_s_mem()), BIO_free_all);
if (!pubkey_bio) throw ecdsa_exception(error::ecdsa_error::create_mem_bio_failed);
if (public_key.substr(0, 27) == "-----BEGIN CERTIFICATE-----") {
auto epkey = helper::extract_pubkey_from_cert(public_key, public_key_password);
const int len = static_cast<int>(epkey.size());
if (BIO_write(pubkey_bio.get(), epkey.data(), len) != len)
throw ecdsa_exception(error::ecdsa_error::load_key_bio_write);
} else {
const int len = static_cast<int>(public_key.size());
if (BIO_write(pubkey_bio.get(), public_key.data(), len) != len)
throw ecdsa_exception(error::ecdsa_error::load_key_bio_write);
}
pkey.reset(PEM_read_bio_EC_PUBKEY(
pubkey_bio.get(), nullptr, nullptr,
(void*)public_key_password
.c_str()), // NOLINT(google-readability-casting) requires `const_cast`
EC_KEY_free);
if (!pkey) throw ecdsa_exception(error::ecdsa_error::load_key_bio_read);
size_t keysize = EC_GROUP_get_degree(EC_KEY_get0_group(pkey.get()));
if (keysize != signature_length * 4 && (signature_length != 132 || keysize != 521))
throw ecdsa_exception(error::ecdsa_error::invalid_key_size);
}
if (!private_key.empty()) {
std::unique_ptr<BIO, decltype(&BIO_free_all)> privkey_bio(BIO_new(BIO_s_mem()), BIO_free_all);
if (!privkey_bio) throw ecdsa_exception(error::ecdsa_error::create_mem_bio_failed);
const int len = static_cast<int>(private_key.size());
if (BIO_write(privkey_bio.get(), private_key.data(), len) != len)
throw ecdsa_exception(error::ecdsa_error::load_key_bio_write);
pkey.reset(PEM_read_bio_ECPrivateKey(privkey_bio.get(), nullptr, nullptr,
const_cast<char*>(private_key_password.c_str())),
EC_KEY_free);
if (!pkey) throw ecdsa_exception(error::ecdsa_error::load_key_bio_read);
size_t keysize = EC_GROUP_get_degree(EC_KEY_get0_group(pkey.get()));
if (keysize != signature_length * 4 && (signature_length != 132 || keysize != 521))
throw ecdsa_exception(error::ecdsa_error::invalid_key_size);
}
if (!pkey) throw ecdsa_exception(error::ecdsa_error::no_key_provided);
if (EC_KEY_check_key(pkey.get()) == 0) throw ecdsa_exception(error::ecdsa_error::invalid_key);
}
/**
* Sign jwt data
* \param data The data to sign
* \param ec error_code filled with details on error
* \return ECDSA signature for the given data
*/
std::string sign(const std::string& data, std::error_code& ec) const {
ec.clear();
const std::string hash = generate_hash(data, ec);
if (ec) return {};
std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(
ECDSA_do_sign(reinterpret_cast<const unsigned char*>(hash.data()), static_cast<int>(hash.size()),
pkey.get()),
ECDSA_SIG_free);
if (!sig) {
ec = error::signature_generation_error::ecdsa_do_sign_failed;
return {};
}
#ifdef OPENSSL10
auto rr = helper::bn2raw(sig->r);
auto rs = helper::bn2raw(sig->s);
#else
const BIGNUM* r;
const BIGNUM* s;
ECDSA_SIG_get0(sig.get(), &r, &s);
auto rr = helper::bn2raw(r);
auto rs = helper::bn2raw(s);
#endif
if (rr.size() > signature_length / 2 || rs.size() > signature_length / 2)
throw std::logic_error("bignum size exceeded expected length");
rr.insert(0, signature_length / 2 - rr.size(), '\0');
rs.insert(0, signature_length / 2 - rs.size(), '\0');
return rr + rs;
}
/**
* Check if signature is valid
* \param data The data to check signature against
* \param signature Signature provided by the jwt
* \param ec Filled with details on error
*/
void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
ec.clear();
const std::string hash = generate_hash(data, ec);
if (ec) return;
auto r = helper::raw2bn(signature.substr(0, signature.size() / 2));
auto s = helper::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(), static_cast<int>(hash.size()), &sig,
pkey.get()) != 1) {
ec = error::signature_verification_error::invalid_signature;
return;
}
#else
std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(ECDSA_SIG_new(), ECDSA_SIG_free);
if (!sig) {
ec = error::signature_verification_error::create_context_failed;
return;
}
ECDSA_SIG_set0(sig.get(), r.release(), s.release());
if (ECDSA_do_verify(reinterpret_cast<const unsigned char*>(hash.data()), static_cast<int>(hash.size()),
sig.get(), pkey.get()) != 1) {
ec = error::signature_verification_error::invalid_signature;
return;
}
#endif
}
/**
* Returns the algorithm name provided to the constructor
* \return algorithm's name
*/
std::string name() const { return alg_name; }
private: