-
Notifications
You must be signed in to change notification settings - Fork 25
/
crypto-algorithm.cpp
1478 lines (1360 loc) · 59.5 KB
/
crypto-algorithm.cpp
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
#include "openssl/rsa.h"
#include "openssl/sha.h"
#include <iostream>
#include <optional>
#include <span>
#include <vector>
#include "crypto-algorithm.h"
#include "crypto-key-rsa-components.h"
#include "js-compute-builtins.h"
namespace builtins {
namespace {
// Web Crypto API uses DOMExceptions to indicate errors
// We are adding the fields which are tested for in Web Platform Tests
// TODO: Implement DOMExceptions class and use that instead of duck-typing on an Error instance
void convertErrorToNotSupported(JSContext *cx) {
MOZ_ASSERT(JS_IsExceptionPending(cx));
JS::RootedValue exn(cx);
if (!JS_GetPendingException(cx, &exn)) {
return;
}
MOZ_ASSERT(exn.isObject());
JS::RootedObject error(cx, &exn.toObject());
JS::RootedValue name(cx, JS::StringValue(JS_NewStringCopyZ(cx, "NotSupportedError")));
JS_SetProperty(cx, error, "name", name);
JS::RootedValue code(cx, JS::NumberValue(9));
JS_SetProperty(cx, error, "code", code);
}
// Web Crypto API uses DOMExceptions to indicate errors
// We are adding the fields which are tested for in Web Platform Tests
// TODO: Implement DOMExceptions class and use that instead of duck-typing on an Error instance
void convertErrorToDataError(JSContext *cx) {
MOZ_ASSERT(JS_IsExceptionPending(cx));
JS::RootedValue exn(cx);
if (!JS_GetPendingException(cx, &exn)) {
return;
}
MOZ_ASSERT(exn.isObject());
JS::RootedObject error(cx, &exn.toObject());
JS::RootedValue name(cx, JS::StringValue(JS_NewStringCopyZ(cx, "DataError")));
JS_SetProperty(cx, error, "name", name);
}
// Web Crypto API uses DOMExceptions to indicate errors
// We are adding the fields which are tested for in Web Platform Tests
// TODO: Implement DOMExceptions class and use that instead of duck-typing on an Error instance
void convertErrorToOperationError(JSContext *cx) {
MOZ_ASSERT(JS_IsExceptionPending(cx));
JS::RootedValue exn(cx);
if (!JS_GetPendingException(cx, &exn)) {
return;
}
MOZ_ASSERT(exn.isObject());
JS::RootedObject error(cx, &exn.toObject());
JS::RootedValue name(cx, JS::StringValue(JS_NewStringCopyZ(cx, "OperationError")));
JS_SetProperty(cx, error, "name", name);
}
void convertErrorToInvalidAccessError(JSContext *cx) {
MOZ_ASSERT(JS_IsExceptionPending(cx));
JS::RootedValue exn(cx);
if (!JS_GetPendingException(cx, &exn)) {
return;
}
MOZ_ASSERT(exn.isObject());
JS::RootedObject error(cx, &exn.toObject());
JS::RootedValue name(cx, JS::StringValue(JS_NewStringCopyZ(cx, "InvalidAccessError")));
JS_SetProperty(cx, error, "name", name);
JS::RootedValue code(cx, JS::NumberValue(15));
JS_SetProperty(cx, error, "code", code);
}
const EVP_MD *createDigestAlgorithm(JSContext *cx, JS::HandleObject key) {
JS::RootedObject alg(cx, CryptoKey::get_algorithm(key));
JS::RootedValue hash_val(cx);
JS_GetProperty(cx, alg, "hash", &hash_val);
if (!hash_val.isObject()) {
JS_ReportErrorLatin1(cx, "NotSupportedError");
convertErrorToNotSupported(cx);
return nullptr;
}
JS::RootedObject hash(cx, &hash_val.toObject());
JS::RootedValue name_val(cx);
JS_GetProperty(cx, hash, "name", &name_val);
size_t name_length;
auto name_chars = encode(cx, name_val, &name_length);
if (!name_chars) {
JS_ReportErrorLatin1(cx, "NotSupportedError");
convertErrorToNotSupported(cx);
return nullptr;
}
std::string_view name(name_chars.get(), name_length);
if (name == "MD5") {
return EVP_md5();
} else if (name == "SHA-1") {
return EVP_sha1();
} else if (name == "SHA-224") {
return EVP_sha224();
} else if (name == "SHA-256") {
return EVP_sha256();
} else if (name == "SHA-384") {
return EVP_sha384();
} else if (name == "SHA-512") {
return EVP_sha512();
} else {
JS_ReportErrorLatin1(cx, "NotSupportedError");
convertErrorToNotSupported(cx);
return nullptr;
}
}
// This implements https://w3c.github.io/webcrypto/#sha-operations for all
// the SHA algorithms that we support.
std::optional<std::vector<uint8_t>> rawDigest(JSContext *cx, std::span<uint8_t> data,
const EVP_MD *algorithm, size_t buffer_size) {
unsigned int size;
std::vector<uint8_t> buf(buffer_size, 0);
if (!EVP_Digest(data.data(), data.size(), buf.data(), &size, algorithm, NULL)) {
// 2. If performing the operation results in an error, then throw an OperationError.
JS_ReportErrorUTF8(cx, "SubtleCrypto.digest: failed to create digest");
convertErrorToOperationError(cx);
return std::nullopt;
}
return {std::move(buf)};
};
// This implements https://w3c.github.io/webcrypto/#sha-operations for all
// the SHA algorithms that we support.
JSObject *digest(JSContext *cx, std::span<uint8_t> data, const EVP_MD *algorithm,
size_t buffer_size) {
unsigned int size;
mozilla::UniquePtr<uint8_t[], JS::FreePolicy> buf{
static_cast<uint8_t *>(JS_malloc(cx, buffer_size))};
if (!buf) {
JS_ReportOutOfMemory(cx);
return nullptr;
}
if (!EVP_Digest(data.data(), data.size(), buf.get(), &size, algorithm, NULL)) {
// 2. If performing the operation results in an error, then throw an OperationError.
JS_ReportErrorUTF8(cx, "SubtleCrypto.digest: failed to create digest");
convertErrorToOperationError(cx);
return nullptr;
}
// 3. Return a new ArrayBuffer containing result.
JS::RootedObject array_buffer(cx);
array_buffer.set(JS::NewArrayBufferWithContents(cx, size, buf.get()));
if (!array_buffer) {
JS_ReportOutOfMemory(cx);
return nullptr;
}
// `array_buffer` now owns `buf`
static_cast<void>(buf.release());
return array_buffer;
};
// https://datatracker.ietf.org/doc/html/rfc7518#section-6.3.1
// 6.3.1. Parameters for RSA Public Keys
std::unique_ptr<CryptoKeyRSAComponents> createRSAPublicKeyFromJWK(JSContext *cx, JsonWebKey *jwk) {
if (!jwk->n.has_value() || !jwk->e.has_value()) {
JS_ReportErrorLatin1(cx, "Data provided to an operation does not meet requirements");
convertErrorToDataError(cx);
return nullptr;
}
auto modulusResult = GlobalProperties::forgivingBase64Decode(
jwk->n.value(), GlobalProperties::base64URLDecodeTable);
if (modulusResult.isErr()) {
JS_ReportErrorLatin1(cx,
"The JWK member 'n' could not be base64url decoded or contained padding");
convertErrorToDataError(cx);
return nullptr;
}
auto modulus = modulusResult.unwrap();
// Per RFC 7518 Section 6.3.1.1: https://tools.ietf.org/html/rfc7518#section-6.3.1.1
if (modulus.starts_with('0')) {
modulus = modulus.erase(0, 1);
}
auto dataResult = GlobalProperties::convertJSValueToByteString(cx, jwk->e.value());
if (dataResult.isErr()) {
JS_ReportErrorLatin1(cx, "Data provided to an operation does not meet requirements");
convertErrorToDataError(cx);
return nullptr;
}
auto data = dataResult.unwrap();
auto exponentResult =
GlobalProperties::forgivingBase64Decode(data, GlobalProperties::base64URLDecodeTable);
if (exponentResult.isErr()) {
JS_ReportErrorLatin1(cx,
"The JWK member 'e' could not be base64url decoded or contained padding");
convertErrorToDataError(cx);
return nullptr;
}
auto exponent = exponentResult.unwrap();
// import public key
auto publicKeyComponents = CryptoKeyRSAComponents::createPublic(modulus, exponent);
return publicKeyComponents;
}
// https://datatracker.ietf.org/doc/html/rfc7518#section-6.3.2
// 6.3.2. Parameters for RSA Private Keys
std::unique_ptr<CryptoKeyRSAComponents> createRSAPrivateKeyFromJWK(JSContext *cx, JsonWebKey *jwk) {
// 2.10.1 If jwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms [JWA],
// then throw a DataError. 2.10.2 Let privateKey represents the RSA private key identified by
// interpreting jwk according to Section 6.3.2 of JSON Web Algorithms [JWA]. 2.10.3 If privateKey
// is not a valid RSA private key according to [RFC3447], then throw a DataError.
auto modulusResult = GlobalProperties::forgivingBase64Decode(
jwk->n.value(), GlobalProperties::base64URLDecodeTable);
if (modulusResult.isErr()) {
JS_ReportErrorLatin1(cx,
"The JWK member 'n' could not be base64url decoded or contained padding");
convertErrorToDataError(cx);
return nullptr;
}
auto modulus = modulusResult.unwrap();
// Per RFC 7518 Section 6.3.1.1: https://tools.ietf.org/html/rfc7518#section-6.3.1.1
if (modulus.starts_with('0')) {
modulus = modulus.erase(0, 1);
}
auto dataResult = GlobalProperties::convertJSValueToByteString(cx, jwk->e.value());
if (dataResult.isErr()) {
JS_ReportErrorLatin1(cx, "Data provided to an operation does not meet requirements");
convertErrorToDataError(cx);
}
auto data = dataResult.unwrap();
auto exponentResult =
GlobalProperties::forgivingBase64Decode(data, GlobalProperties::base64URLDecodeTable);
if (exponentResult.isErr()) {
JS_ReportErrorLatin1(cx,
"The JWK member 'e' could not be base64url decoded or contained padding");
convertErrorToDataError(cx);
return nullptr;
}
auto exponent = exponentResult.unwrap();
auto privateExponentResult = GlobalProperties::forgivingBase64Decode(
jwk->d.value(), GlobalProperties::base64URLDecodeTable);
if (privateExponentResult.isErr()) {
JS_ReportErrorLatin1(cx,
"The JWK member 'd' could not be base64url decoded or contained padding");
convertErrorToDataError(cx);
return nullptr;
}
auto privateExponent = privateExponentResult.unwrap();
if (!jwk->p.has_value() && !jwk->q.has_value() && !jwk->dp.has_value() && !jwk->dp.has_value() &&
!jwk->qi.has_value()) {
auto privateKeyComponents =
CryptoKeyRSAComponents::createPrivate(modulus, exponent, privateExponent);
return privateKeyComponents;
}
if (!jwk->p.has_value() || !jwk->q.has_value() || !jwk->dp.has_value() || !jwk->dq.has_value() ||
!jwk->qi.has_value()) {
JS_ReportErrorLatin1(cx, "Data provided to an operation does not meet requirements");
convertErrorToDataError(cx);
return nullptr;
}
auto firstPrimeFactorResult = GlobalProperties::forgivingBase64Decode(
jwk->p.value(), GlobalProperties::base64URLDecodeTable);
if (firstPrimeFactorResult.isErr()) {
JS_ReportErrorLatin1(cx,
"The JWK member 'p' could not be base64url decoded or contained padding");
convertErrorToDataError(cx);
return nullptr;
}
auto firstPrimeFactor = firstPrimeFactorResult.unwrap();
auto firstFactorCRTExponentResult = GlobalProperties::forgivingBase64Decode(
jwk->dp.value(), GlobalProperties::base64URLDecodeTable);
if (firstFactorCRTExponentResult.isErr()) {
JS_ReportErrorLatin1(cx,
"The JWK member 'dp' could not be base64url decoded or contained padding");
convertErrorToDataError(cx);
return nullptr;
}
auto firstFactorCRTExponent = firstFactorCRTExponentResult.unwrap();
auto secondPrimeFactorResult = GlobalProperties::forgivingBase64Decode(
jwk->q.value(), GlobalProperties::base64URLDecodeTable);
if (secondPrimeFactorResult.isErr()) {
JS_ReportErrorLatin1(cx,
"The JWK member 'q' could not be base64url decoded or contained padding");
convertErrorToDataError(cx);
return nullptr;
}
auto secondPrimeFactor = secondPrimeFactorResult.unwrap();
auto secondFactorCRTExponentResult = GlobalProperties::forgivingBase64Decode(
jwk->dq.value(), GlobalProperties::base64URLDecodeTable);
if (secondFactorCRTExponentResult.isErr()) {
JS_ReportErrorLatin1(cx,
"The JWK member 'dq' could not be base64url decoded or contained padding");
convertErrorToDataError(cx);
return nullptr;
}
auto secondFactorCRTExponent = secondFactorCRTExponentResult.unwrap();
auto secondFactorCRTCoefficientResult = GlobalProperties::forgivingBase64Decode(
jwk->qi.value(), GlobalProperties::base64URLDecodeTable);
if (secondFactorCRTCoefficientResult.isErr()) {
JS_ReportErrorLatin1(cx,
"The JWK member 'qi' could not be base64url decoded or contained padding");
convertErrorToDataError(cx);
return nullptr;
}
auto secondFactorCRTCoefficient = secondFactorCRTCoefficientResult.unwrap();
CryptoKeyRSAComponents::PrimeInfo firstPrimeInfo{firstPrimeFactor, firstFactorCRTExponent};
CryptoKeyRSAComponents::PrimeInfo secondPrimeInfo{secondPrimeFactor, secondFactorCRTExponent,
secondFactorCRTCoefficient};
if (!jwk->oth.size()) {
auto privateKeyComponents = CryptoKeyRSAComponents::createPrivateWithAdditionalData(
modulus, exponent, privateExponent, firstPrimeInfo, secondPrimeInfo, {});
return privateKeyComponents;
}
std::vector<CryptoKeyRSAComponents::PrimeInfo> otherPrimeInfos;
for (const auto &value : jwk->oth) {
auto primeFactorResult =
GlobalProperties::forgivingBase64Decode(value.r, GlobalProperties::base64URLDecodeTable);
if (primeFactorResult.isErr()) {
return nullptr;
}
auto primeFactor = primeFactorResult.unwrap();
auto factorCRTExponentResult =
GlobalProperties::forgivingBase64Decode(value.d, GlobalProperties::base64URLDecodeTable);
if (factorCRTExponentResult.isErr()) {
return nullptr;
}
auto factorCRTExponent = factorCRTExponentResult.unwrap();
auto factorCRTCoefficientResult =
GlobalProperties::forgivingBase64Decode(value.t, GlobalProperties::base64URLDecodeTable);
if (factorCRTCoefficientResult.isErr()) {
return nullptr;
}
auto factorCRTCoefficient = factorCRTCoefficientResult.unwrap();
otherPrimeInfos.emplace_back(primeFactor, factorCRTExponent, factorCRTCoefficient);
}
auto privateKeyComponents = CryptoKeyRSAComponents::createPrivateWithAdditionalData(
modulus, exponent, privateExponent, firstPrimeInfo, secondPrimeInfo, otherPrimeInfos);
return privateKeyComponents;
}
JS::Result<builtins::CryptoAlgorithmIdentifier> toHashIdentifier(JSContext *cx,
JS::HandleValue value) {
auto normalizedHashAlgorithm = CryptoAlgorithmDigest::normalize(cx, value);
if (!normalizedHashAlgorithm) {
return JS::Result<builtins::CryptoAlgorithmIdentifier>(JS::Error());
}
return normalizedHashAlgorithm->identifier();
}
// This implements the first section of
// https://w3c.github.io/webcrypto/#algorithm-normalization-normalize-an-algorithm which is shared
// across all the diffent algorithms, but importantly does not implement the parts to do with the
// chosen `op` (operation) the `op` parts are handled in the specialized `normalize` functions on
// the concrete classes which derive from CryptoAlgorithm such as CryptoAlgorithmDigest.
JS::Result<CryptoAlgorithmIdentifier> normalizeIdentifier(JSContext *cx, JS::HandleValue value) {
// The specification states:
// --------
// If alg is an instance of a DOMString:
// Return the result of running the normalize an algorithm algorithm,
// with the alg set to a new Algorithm dictionary whose name attribute
// is alg, and with the op set to op.
// --------
// Instead of doing that, we operate on the string and not the dictionary.
// If we see a dictionary (JSObject), we pull the name attribute out
// and coerce it's value to a String.
// The reason we chose this direct is because we only need this one field
// from the provided dictionary, so we store the field on it's own and not
// in a JSObject which would take up more memory.
// 1. Let registeredAlgorithms be the associative container stored at the op key of
// supportedAlgorithms.
// 2. Let initialAlg be the result of converting the ECMAScript object represented by alg to the
// IDL dictionary type Algorithm, as defined by [WebIDL].
// 3. If an error occurred, return the error and terminate this algorithm.
// 4. Let algName be the value of the name attribute of initialAlg.
JS::Rooted<JSString *> algName(cx);
if (value.isObject()) {
JS::Rooted<JSObject *> params(cx, &value.toObject());
JS::Rooted<JS::Value> name_val(cx);
if (!JS_GetProperty(cx, params, "name", &name_val)) {
return JS::Result<CryptoAlgorithmIdentifier>(JS::Error());
}
algName.set(JS::ToString(cx, name_val));
} else {
algName.set(JS::ToString(cx, value));
}
// If `algName` is falsey, it means the call to JS::ToString failed.
// In that scenario, we should already have an exception, which is why we are not creating our own
// one.
if (!algName) {
return JS::Result<CryptoAlgorithmIdentifier>(JS::Error());
}
// TODO: We convert from JSString to std::string quite a lot in the codebase, should we pull this
// logic out into a new function?
size_t algorithmLen;
JS::UniqueChars algorithmChars = encode(cx, algName, &algorithmLen);
if (!algorithmChars) {
return JS::Result<CryptoAlgorithmIdentifier>(JS::Error());
}
std::string algorithm(algorithmChars.get(), algorithmLen);
// 5. If registeredAlgorithms contains a key that is a case-insensitive string match for algName:
// 5.1 Set algName to the value of the matching key.
// 5.2 Let desiredType be the IDL dictionary type stored at algName in registeredAlgorithms.
// Note: We do not implement 5.2 here, it is instead implemented in the specialized `normalize`
// functions.
std::transform(algorithm.begin(), algorithm.end(), algorithm.begin(),
[](unsigned char c) { return std::toupper(c); });
if (algorithm == "RSASSA-PKCS1-V1_5") {
return CryptoAlgorithmIdentifier::RSASSA_PKCS1_v1_5;
} else if (algorithm == "RSA-PSS") {
return CryptoAlgorithmIdentifier::RSA_PSS;
} else if (algorithm == "RSA-OAEP") {
return CryptoAlgorithmIdentifier::RSA_OAEP;
} else if (algorithm == "ECDSA") {
return CryptoAlgorithmIdentifier::ECDSA;
} else if (algorithm == "ECDH") {
return CryptoAlgorithmIdentifier::ECDH;
} else if (algorithm == "AES-CTR") {
return CryptoAlgorithmIdentifier::AES_CTR;
} else if (algorithm == "AES-CBC") {
return CryptoAlgorithmIdentifier::AES_CBC;
} else if (algorithm == "AES-GCM") {
return CryptoAlgorithmIdentifier::AES_GCM;
} else if (algorithm == "AES-KW") {
return CryptoAlgorithmIdentifier::AES_KW;
} else if (algorithm == "HMAC") {
return CryptoAlgorithmIdentifier::HMAC;
} else if (algorithm == "MD5") {
return CryptoAlgorithmIdentifier::MD5;
} else if (algorithm == "SHA-1") {
return CryptoAlgorithmIdentifier::SHA_1;
} else if (algorithm == "SHA-256") {
return CryptoAlgorithmIdentifier::SHA_256;
} else if (algorithm == "SHA-384") {
return CryptoAlgorithmIdentifier::SHA_384;
} else if (algorithm == "SHA-512") {
return CryptoAlgorithmIdentifier::SHA_512;
} else if (algorithm == "HKDF") {
return CryptoAlgorithmIdentifier::HKDF;
} else if (algorithm == "PBKDF2") {
return CryptoAlgorithmIdentifier::PBKDF2;
} else {
// Otherwise: Return a new NotSupportedError and terminate this algorithm.
JS_ReportErrorUTF8(cx, "Algorithm: Unrecognized name");
convertErrorToNotSupported(cx);
return JS::Result<CryptoAlgorithmIdentifier>(JS::Error());
}
}
} // namespace
const char *algorithmName(CryptoAlgorithmIdentifier algorithm) {
switch (algorithm) {
case CryptoAlgorithmIdentifier::RSASSA_PKCS1_v1_5: {
return "RSASSA-PKCS1-v1_5";
}
case CryptoAlgorithmIdentifier::RSA_PSS: {
return "RSA-PSS";
}
case CryptoAlgorithmIdentifier::RSA_OAEP: {
return "RSA-OAEP";
}
case CryptoAlgorithmIdentifier::ECDSA: {
return "ECDSA";
}
case CryptoAlgorithmIdentifier::ECDH: {
return "ECDH";
}
case CryptoAlgorithmIdentifier::AES_CTR: {
return "AES-CTR";
}
case CryptoAlgorithmIdentifier::AES_CBC: {
return "AES-CBC";
}
case CryptoAlgorithmIdentifier::AES_GCM: {
return "AES-GCM";
}
case CryptoAlgorithmIdentifier::AES_KW: {
return "AES-KW";
}
case CryptoAlgorithmIdentifier::HMAC: {
return "HMAC";
}
case CryptoAlgorithmIdentifier::MD5: {
return "MD5";
}
case CryptoAlgorithmIdentifier::SHA_1: {
return "SHA-1";
}
case CryptoAlgorithmIdentifier::SHA_256: {
return "SHA-256";
}
case CryptoAlgorithmIdentifier::SHA_384: {
return "SHA-384";
}
case CryptoAlgorithmIdentifier::SHA_512: {
return "SHA-512";
}
case CryptoAlgorithmIdentifier::HKDF: {
return "HKDF";
}
case CryptoAlgorithmIdentifier::PBKDF2: {
return "PBKDF2";
}
default: {
MOZ_ASSERT_UNREACHABLE("Unknown `CryptoAlgorithmIdentifier` value");
}
}
}
// clang-format off
/// This table is from https://w3c.github.io/webcrypto/#h-note-15
// | Algorithm | encrypt | decrypt | sign | verify | digest | generateKey | deriveKey | deriveBits | importKey | exportKey | wrapKey | unwrapKey |
// | RSASSA-PKCS1-v1_5 | | | ✔ | ✔ | | ✔ | | | ✔ | ✔ | | |
// | RSA-PSS | | | ✔ | ✔ | | ✔ | | | ✔ | ✔ | | |
// | RSA-OAEP | ✔ | ✔ | | | | ✔ | | | ✔ | ✔ | ✔ | ✔ |
// | ECDSA | | | ✔ | ✔ | | ✔ | | | ✔ | ✔ | | |
// | ECDH | | | | | | ✔ | ✔ | ✔ | ✔ | ✔ | | |
// | AES-CTR | ✔ | ✔ | | | | ✔ | | | ✔ | ✔ | ✔ | ✔ |
// | AES-CBC | ✔ | ✔ | | | | ✔ | | | ✔ | ✔ | ✔ | ✔ |
// | AES-GCM | ✔ | ✔ | | | | ✔ | | | ✔ | ✔ | ✔ | ✔ |
// | AES-KW | | | | | | ✔ | | | ✔ | ✔ | ✔ | ✔ |
// | HMAC | | | ✔ | ✔ | | ✔ | | | ✔ | ✔ | | |
// | SHA-1 | | | | | ✔ | | | | | | | |
// | SHA-256 | | | | | ✔ | | | | | | | |
// | SHA-384 | | | | | ✔ | | | | | | | |
// | SHA-512 | | | | | ✔ | | | | | | | |
// | HKDF | | | | | | | ✔ | ✔ | ✔ | | | |
// | PBKDF2 | | | | | | | ✔ | ✔ | ✔ | | | |
//clang-format on
std::unique_ptr<CryptoAlgorithmDigest> CryptoAlgorithmDigest::normalize(JSContext *cx,
JS::HandleValue value) {
// Do steps 1 through 5.1 of https://w3c.github.io/webcrypto/#algorithm-normalization-normalize-an-algorithm
auto identifierResult = normalizeIdentifier(cx, value);
if (identifierResult.isErr()) {
// If we are here, this means either the identifier could not be coerced to a String or was not recognized
// In both those scenarios an exception will have already been created, which is why we are not creating one here.
return nullptr;
}
auto identifier = identifierResult.unwrap();
// The table listed at https://w3c.github.io/webcrypto/#h-note-15 is what defines which algorithms support which operations
// SHA-1, SHA-256, SHA-384, and SHA-512 are the only algorithms which support the digest operation
// We also support MD5 as an extra implementor defined algorithm
// Note: The specification states that none of the SHA algorithms take any parameters -- https://w3c.github.io/webcrypto/#sha-registration
switch (identifier) {
case CryptoAlgorithmIdentifier::MD5: {
return std::make_unique<CryptoAlgorithmMD5>();
}
case CryptoAlgorithmIdentifier::SHA_1: {
return std::make_unique<CryptoAlgorithmSHA1>();
}
case CryptoAlgorithmIdentifier::SHA_256: {
return std::make_unique<CryptoAlgorithmSHA256>();
}
case CryptoAlgorithmIdentifier::SHA_384: {
return std::make_unique<CryptoAlgorithmSHA384>();
}
case CryptoAlgorithmIdentifier::SHA_512: {
return std::make_unique<CryptoAlgorithmSHA512>();
}
default: {
JS_ReportErrorASCII(cx, "Supplied algorithm does not support the digest operation");
convertErrorToNotSupported(cx);
return nullptr;
}
}
};
std::unique_ptr<CryptoAlgorithmSignVerify>
CryptoAlgorithmSignVerify::normalize(JSContext *cx, JS::HandleValue value) {
// Do steps 1 through 5.1 of https://w3c.github.io/webcrypto/#algorithm-normalization-normalize-an-algorithm
auto identifierResult = normalizeIdentifier(cx, value);
if (identifierResult.isErr()) {
// If we are here, this means either the identifier could not be coerced to a String or was not recognized
// In both those scenarios an exception will have already been created, which is why we are not creating one here.
return nullptr;
}
auto identifier = identifierResult.unwrap();
JS::Rooted<JSObject *> params(cx);
// The value can either be a JS String or a JS Object with a 'name' property which is the algorithm identifier.
// Other properties within the object will be the parameters for the algorithm to use.
if (value.isString()) {
auto obj = JS_NewPlainObject(cx);
params.set(obj);
if (!JS_SetProperty(cx, params, "name", value)) {
return nullptr;
}
} else if (value.isObject()) {
params.set(&value.toObject());
}
// The table listed at https://w3c.github.io/webcrypto/#h-note-15 is what defines which algorithms support which operations
// RSASSA-PKCS1-v1_5, RSA-PSS, ECDSA, HMAC, are the algorithms
// which support the sign operation
switch (identifier) {
case CryptoAlgorithmIdentifier::RSASSA_PKCS1_v1_5: {
return std::make_unique<CryptoAlgorithmRSASSA_PKCS1_v1_5_Sign_Verify>();
}
case CryptoAlgorithmIdentifier::HMAC: {
return std::make_unique<CryptoAlgorithmHMAC_Sign_Verify>();
}
case CryptoAlgorithmIdentifier::ECDSA:
case CryptoAlgorithmIdentifier::RSA_PSS: {
MOZ_ASSERT(false);
JS_ReportErrorASCII(cx, "Supplied algorithm is not yet supported");
convertErrorToNotSupported(cx);
return nullptr;
}
default: {
return nullptr;
}
}
};
namespace {
std::optional<std::pair<mozilla::UniquePtr<uint8_t[], JS::FreePolicy>, size_t>> hmacSignature(JSContext *cx,
const EVP_MD* algorithm, const std::span<uint8_t>& keyData, const std::span<uint8_t> data) {
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
if (!ctx) {
return std::nullopt;
}
EVP_PKEY * hkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, nullptr, keyData.data(), keyData.size());
if (!hkey) {
return std::nullopt;
}
if (1 != EVP_DigestSignInit(ctx, nullptr, algorithm, nullptr, hkey)) {
return std::nullopt;
}
if (1 != EVP_DigestSignUpdate(ctx, data.data(), data.size())) {
return std::nullopt;
}
size_t len = 0;
if (1 != EVP_DigestSignFinal(ctx, nullptr, &len)) {
return std::nullopt;
}
mozilla::UniquePtr<uint8_t[], JS::FreePolicy> cipherText{static_cast<uint8_t *>(JS_malloc(cx, len))};
if (!cipherText) {
JS_ReportOutOfMemory(cx);
return std::nullopt;
}
if (1 != EVP_DigestSignFinal(ctx, cipherText.get(), &len)) {
return std::nullopt;
}
return std::pair<mozilla::UniquePtr<uint8_t[], JS::FreePolicy>, size_t>(std::move(cipherText), len);
}
}
JSObject *CryptoAlgorithmHMAC_Sign_Verify::sign(JSContext *cx, JS::HandleObject key, std::span<uint8_t> data) {
MOZ_ASSERT(CryptoKey::is_instance(key));
// 1. Let mac be the result of performing the MAC Generation operation described in Section 4 of [FIPS-198-1] using the key represented by [[handle]] internal slot of key, the hash function identified by the hash attribute of the [[algorithm]] internal slot of key and message as the input data text.
const EVP_MD *algorithm = createDigestAlgorithm(cx, key);
if (!algorithm) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return nullptr;
}
std::span<uint8_t> keyData = CryptoKey::hmacKeyData(key);
auto result = hmacSignature(cx, algorithm, keyData, data);
if (!result.has_value()) {
JS_ReportErrorUTF8(cx, "SubtleCrypto.sign: failed to sign");
convertErrorToOperationError(cx);
return nullptr;
}
auto sig = std::move(result.value().first);
auto size = std::move(result.value().second);
// 2. Return a new ArrayBuffer object, associated with the relevant global object of this [HTML], and containing the bytes of mac.
JS::RootedObject array_buffer(cx);
array_buffer.set(JS::NewArrayBufferWithContents(cx, size, sig.get()));
if (!array_buffer) {
JS_ReportOutOfMemory(cx);
return nullptr;
}
// `array_buffer` now owns `sig`
static_cast<void>(sig.release());
return array_buffer;
};
JS::Result<bool> CryptoAlgorithmHMAC_Sign_Verify::verify(JSContext *cx, JS::HandleObject key, std::span<uint8_t> signature, std::span<uint8_t> data) {
MOZ_ASSERT(CryptoKey::is_instance(key));
// 1. Let mac be the result of performing the MAC Generation operation described in Section 4 of [FIPS-198-1] using the key represented by [[handle]] internal slot of key, the hash function identified by the hash attribute of the [[algorithm]] internal slot of key and message as the input data text.
const EVP_MD *algorithm = createDigestAlgorithm(cx, key);
if (!algorithm) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return JS::Result<bool>(JS::Error());
}
std::span<uint8_t> keyData = CryptoKey::hmacKeyData(key);
auto result = hmacSignature(cx, algorithm, keyData, data);
if (!result.has_value()) {
JS_ReportErrorUTF8(cx, "SubtleCrypto.verify: failed to verify");
convertErrorToOperationError(cx);
return JS::Result<bool>(JS::Error());
}
auto sig = std::move(result.value().first);
auto size = std::move(result.value().second);
// 2. Return true if mac is equal to signature and false otherwise.
bool match = size == signature.size() && (CRYPTO_memcmp(sig.get(), signature.data(), size) == 0);
return match;
};
JSObject *CryptoAlgorithmHMAC_Sign_Verify::toObject(JSContext *cx) {
return nullptr;
};
JSObject *CryptoAlgorithmRSASSA_PKCS1_v1_5_Sign_Verify::sign(JSContext *cx, JS::HandleObject key,
std::span<uint8_t> data) {
// 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
if (CryptoKey::type(key) != CryptoKeyType::Private) {
JS_ReportErrorLatin1(cx, "InvalidAccessError");
convertErrorToInvalidAccessError(cx);
return nullptr;
}
MOZ_ASSERT(CryptoKey::is_instance(key));
if (CryptoKey::type(key) != CryptoKeyType::Private) {
JS_ReportErrorLatin1(cx, "InvalidAccessError");
convertErrorToInvalidAccessError(cx);
return nullptr;
}
const EVP_MD *algorithm = createDigestAlgorithm(cx, key);
if (!algorithm) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return nullptr;
}
auto digest = ::builtins::rawDigest(cx, data, algorithm, EVP_MD_size(algorithm));
if (!digest.has_value()) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return nullptr;
}
// 2. Perform the signature generation operation defined in Section 8.2 of [RFC3447] with the
// key represented by the [[handle]] internal slot of key as the signer's private key and the
// contents of message as M and using the hash function specified in the hash attribute of the
// [[algorithm]] internal slot of key as the Hash option for the EMSA-PKCS1-v1_5 encoding
// method.
// 3. If performing the operation results in an error, then throw an OperationError.
auto ctx = EVP_PKEY_CTX_new(CryptoKey::key(key), nullptr);
if (!ctx) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return nullptr;
}
if (EVP_PKEY_sign_init(ctx) <= 0) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return nullptr;
}
if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return nullptr;
}
if (EVP_PKEY_CTX_set_signature_md(ctx, algorithm) <= 0) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return nullptr;
}
size_t signature_length;
if (EVP_PKEY_sign(ctx, nullptr, &signature_length, digest->data(), digest->size()) <= 0) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return nullptr;
}
// 4. Let signature be the value S that results from performing the operation.
mozilla::UniquePtr<uint8_t[], JS::FreePolicy> signature{static_cast<uint8_t *>(JS_malloc(cx, signature_length))};
if (EVP_PKEY_sign(ctx, signature.get(), &signature_length, digest->data(), digest->size()) <= 0) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return nullptr;
}
// 5. Return a new ArrayBuffer associated with the relevant global object of this [HTML], and
// containing the bytes of signature.
JS::RootedObject buffer(cx, JS::NewArrayBufferWithContents(cx, signature_length, signature.get()));
if (!buffer) {
// We can be here is the array buffer was too large -- if that was the case then a
// JSMSG_BAD_ARRAY_LENGTH will have been created. No other failure scenarios in this path will
// create a JS exception and so we need to create one.
if (!JS_IsExceptionPending(cx)) {
// TODO Rename error to InternalError
JS_ReportErrorLatin1(cx, "InternalError");
}
return nullptr;
}
// `signature` is now owned by `buffer`
static_cast<void>(signature.release());
return buffer;
}
JS::Result<bool> CryptoAlgorithmRSASSA_PKCS1_v1_5_Sign_Verify::verify(JSContext *cx, JS::HandleObject key,
std::span<uint8_t> signature,
std::span<uint8_t> data) {
MOZ_ASSERT(CryptoKey::is_instance(key));
if (CryptoKey::type(key) != CryptoKeyType::Public) {
JS_ReportErrorLatin1(cx, "InvalidAccessError");
convertErrorToInvalidAccessError(cx);
return JS::Result<bool>(JS::Error());
}
const EVP_MD *algorithm = createDigestAlgorithm(cx, key);
auto digestOption = ::builtins::rawDigest(cx, data, algorithm, EVP_MD_size(algorithm));
if (!digestOption.has_value()) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return JS::Result<bool>(JS::Error());
}
auto digest = digestOption.value();
auto ctx = EVP_PKEY_CTX_new(CryptoKey::key(key), nullptr);
if (!ctx) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return JS::Result<bool>(JS::Error());
}
if (EVP_PKEY_verify_init(ctx) != 1) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return JS::Result<bool>(JS::Error());
}
if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) != 1) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return JS::Result<bool>(JS::Error());
}
if (EVP_PKEY_CTX_set_signature_md(ctx, algorithm) != 1) {
JS_ReportErrorLatin1(cx, "OperationError");
convertErrorToOperationError(cx);
return JS::Result<bool>(JS::Error());
}
return EVP_PKEY_verify(ctx, signature.data(), signature.size(), digest.data(), digest.size()) ==
1;
}
std::unique_ptr<CryptoAlgorithmImportKey>
CryptoAlgorithmImportKey::normalize(JSContext *cx, JS::HandleValue value) {
// Do steps 1 through 5.1 of https://w3c.github.io/webcrypto/#algorithm-normalization-normalize-an-algorithm
auto identifierResult = normalizeIdentifier(cx, value);
if (identifierResult.isErr()) {
// If we are here, this means either the identifier could not be coerced to a String or was not recognized
// In both those scenarios an exception will have already been created, which is why we are not creating one here.
return nullptr;
}
auto identifier = identifierResult.unwrap();
JS::RootedObject params(cx);
// The value can either be a JS String or a JS Object with a 'name' property which is the algorithm identifier.
// Other properties within the object will be the parameters for the algorithm to use.
if (value.isString()) {
auto obj = JS_NewPlainObject(cx);
params.set(obj);
JS_SetProperty(cx, params, "name", value);
} else if (value.isObject()) {
params.set(&value.toObject());
}
// The table listed at https://w3c.github.io/webcrypto/#h-note-15 is what defines which algorithms support which operations
// RSASSA-PKCS1-v1_5, RSA-PSS, RSA-OAEP, ECDSA, ECDH, AES-CTR, AES-CBC, AES-GCM, AES-KW, HMAC, HKDF, PBKDF2 are the algorithms
// which support the importKey operation
switch (identifier) {
case CryptoAlgorithmIdentifier::RSASSA_PKCS1_v1_5: {
return CryptoAlgorithmRSASSA_PKCS1_v1_5_Import::fromParameters(cx, params);
}
case CryptoAlgorithmIdentifier::HMAC: {
return CryptoAlgorithmHMAC_Import::fromParameters(cx, params);
}
case CryptoAlgorithmIdentifier::RSA_PSS:
case CryptoAlgorithmIdentifier::RSA_OAEP:
case CryptoAlgorithmIdentifier::AES_CTR:
case CryptoAlgorithmIdentifier::AES_CBC:
case CryptoAlgorithmIdentifier::AES_GCM:
case CryptoAlgorithmIdentifier::AES_KW:
case CryptoAlgorithmIdentifier::ECDSA:
case CryptoAlgorithmIdentifier::ECDH:
case CryptoAlgorithmIdentifier::HKDF:
case CryptoAlgorithmIdentifier::PBKDF2: {
MOZ_ASSERT(false);
JS_ReportErrorASCII(cx, "Supplied algorithm is not yet supported");
convertErrorToNotSupported(cx);
return nullptr;
}
default: {
JS_ReportErrorASCII(cx, "Supplied algorithm does not support the importKey operation");
convertErrorToNotSupported(cx);
return nullptr;
}
}
};
std::unique_ptr<CryptoAlgorithmHMAC_Import> CryptoAlgorithmHMAC_Import::fromParameters(JSContext *cx, JS::HandleObject parameters) {
JS::Rooted<JS::Value> hash_val(cx);
if (!JS_GetProperty(cx, parameters, "hash", &hash_val)) {
return nullptr;
}
auto hashIdentifier = toHashIdentifier(cx, hash_val);
if (hashIdentifier.isErr()) {
return nullptr;
}
bool found;
unsigned long length;
if (!JS_HasProperty(cx, parameters, "length", &found)) {
return nullptr;
}
if (found) {
JS::Rooted<JS::Value> length_val(cx);
if (!JS_GetProperty(cx, parameters, "length", &length_val)) {
return nullptr;
}
if (!length_val.isNumber()) {
return nullptr;
}
length = length_val.toNumber();
return std::make_unique<CryptoAlgorithmHMAC_Import>(hashIdentifier.unwrap(), length);
} else {
return std::make_unique<CryptoAlgorithmHMAC_Import>(hashIdentifier.unwrap());
}
}
// https://w3c.github.io/webcrypto/#hmac-operations
JSObject *CryptoAlgorithmHMAC_Import::importKey(JSContext *cx, CryptoKeyFormat format,
KeyData keyData, bool extractable,
CryptoKeyUsages usages) {
MOZ_ASSERT(cx);
JS::RootedObject result(cx);
// 2. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError.
if (!usages.canOnlySignOrVerify()) {
// TODO Rename error to SyntaxError
JS_ReportErrorLatin1(cx, "HMAC keys only support 'sign' and 'verify' operations");
return nullptr;
}
std::unique_ptr<std::span<uint8_t>> data;
// 3. Let hash be a new KeyAlgorithm.
// 4.
switch (format) {
// 5. If format is "raw":
case CryptoKeyFormat::Raw: {
// 5.1 Let data be the octet string contained in keyData.
data = std::make_unique<std::span<uint8_t>>(std::get<std::span<uint8_t>>(keyData));
if (!data) {
JS_ReportErrorLatin1(cx, "Supplied keyData must be either an ArrayBuffer, TypedArray, or DataView.");
convertErrorToDataError(cx);
return nullptr;
}
// 5.2 Set hash to equal the hash member of normalizedAlgorithm.
// Step 5.2 is done in the call to CryptoKey::createHMAC
break;
}
//6. If format is "jwk":
case CryptoKeyFormat::Jwk: {