forked from letsencrypt/boulder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verify_test.go
1599 lines (1467 loc) · 52.1 KB
/
verify_test.go
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
package wfe2
import (
"context"
"crypto"
"crypto/dsa"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"fmt"
"net/http"
"strings"
"testing"
"github.com/letsencrypt/boulder/core"
corepb "github.com/letsencrypt/boulder/core/proto"
bgrpc "github.com/letsencrypt/boulder/grpc"
"github.com/letsencrypt/boulder/mocks"
"github.com/letsencrypt/boulder/probs"
sapb "github.com/letsencrypt/boulder/sa/proto"
"github.com/letsencrypt/boulder/test"
"github.com/letsencrypt/boulder/web"
"github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc"
"gopkg.in/square/go-jose.v2"
)
// sigAlgForKey uses `signatureAlgorithmForKey` but fails immediately using the
// testing object if the sig alg is unknown.
func sigAlgForKey(t *testing.T, key interface{}) jose.SignatureAlgorithm {
var sigAlg jose.SignatureAlgorithm
var err error
// Gracefully handle the case where a non-pointer public key is given where
// sigAlgorithmForKey always wants a pointer. It may be tempting to try and do
// `sigAlgorithmForKey(&jose.JSONWebKey{Key: &key})` without a type switch but this produces
// `*interface {}` and not the desired `*rsa.PublicKey` or `*ecdsa.PublicKey`.
switch k := key.(type) {
case rsa.PublicKey:
sigAlg, err = sigAlgorithmForKey(&jose.JSONWebKey{Key: &k})
case ecdsa.PublicKey:
sigAlg, err = sigAlgorithmForKey(&jose.JSONWebKey{Key: &k})
default:
sigAlg, err = sigAlgorithmForKey(&jose.JSONWebKey{Key: k})
}
test.Assert(t, err == nil, fmt.Sprintf("Error getting signature algorithm for key %#v", key))
return sigAlg
}
// keyAlgForKey returns a JWK key algorithm based on the provided private key.
// Only ECDSA and RSA private keys are supported.
func keyAlgForKey(t *testing.T, key interface{}) string {
switch key.(type) {
case *rsa.PrivateKey, rsa.PrivateKey:
return "RSA"
case *ecdsa.PrivateKey, ecdsa.PrivateKey:
return "ECDSA"
}
t.Fatalf("Can't figure out keyAlgForKey: %#v", key)
return ""
}
// pubKeyForKey returns the public key of an RSA/ECDSA private key provided as
// argument.
func pubKeyForKey(t *testing.T, privKey interface{}) interface{} {
switch k := privKey.(type) {
case *rsa.PrivateKey:
return k.PublicKey
case *ecdsa.PrivateKey:
return k.PublicKey
}
t.Fatalf("Unable to get public key for private key %#v", privKey)
return nil
}
// signRequestEmbed creates a JWS for a given request body with an embedded JWK
// corresponding to the private key provided. The URL and nonce extra headers
// are set based on the additional arguments. A computed JWS, the corresponding
// embedded JWK and the JWS in serialized string form are returned.
func signRequestEmbed(
t *testing.T,
privateKey interface{},
url string,
req string,
nonceService jose.NonceSource) (*jose.JSONWebSignature, *jose.JSONWebKey, string) {
// if no key is provided default to test1KeyPrivatePEM
var publicKey interface{}
if privateKey == nil {
signer := loadKey(t, []byte(test1KeyPrivatePEM))
privateKey = signer
publicKey = signer.Public()
} else {
publicKey = pubKeyForKey(t, privateKey)
}
signerKey := jose.SigningKey{
Key: privateKey,
Algorithm: sigAlgForKey(t, publicKey),
}
opts := &jose.SignerOptions{
NonceSource: nonceService,
EmbedJWK: true,
}
if url != "" {
opts.ExtraHeaders = map[jose.HeaderKey]interface{}{
"url": url,
}
}
signer, err := jose.NewSigner(signerKey, opts)
test.AssertNotError(t, err, "Failed to make signer")
jws, err := signer.Sign([]byte(req))
test.AssertNotError(t, err, "Failed to sign req")
body := jws.FullSerialize()
parsedJWS, err := jose.ParseSigned(body)
test.AssertNotError(t, err, "Failed to parse generated JWS")
return parsedJWS, parsedJWS.Signatures[0].Header.JSONWebKey, body
}
// signRequestKeyID creates a JWS for a given request body with key ID specified
// based on the ID number provided. The URL and nonce extra headers
// are set based on the additional arguments. A computed JWS, the corresponding
// embedded JWK and the JWS in serialized string form are returned.
func signRequestKeyID(
t *testing.T,
keyID int64,
privateKey interface{},
url string,
req string,
nonceService jose.NonceSource) (*jose.JSONWebSignature, *jose.JSONWebKey, string) {
// if no key is provided default to test1KeyPrivatePEM
if privateKey == nil {
privateKey = loadKey(t, []byte(test1KeyPrivatePEM))
}
jwk := &jose.JSONWebKey{
Key: privateKey,
Algorithm: keyAlgForKey(t, privateKey),
KeyID: fmt.Sprintf("http://localhost/acme/acct/%d", keyID),
}
signerKey := jose.SigningKey{
Key: jwk,
Algorithm: jose.RS256,
}
opts := &jose.SignerOptions{
NonceSource: nonceService,
ExtraHeaders: map[jose.HeaderKey]interface{}{
"url": url,
},
}
signer, err := jose.NewSigner(signerKey, opts)
test.AssertNotError(t, err, "Failed to make signer")
jws, err := signer.Sign([]byte(req))
test.AssertNotError(t, err, "Failed to sign req")
body := jws.FullSerialize()
parsedJWS, err := jose.ParseSigned(body)
test.AssertNotError(t, err, "Failed to parse generated JWS")
return parsedJWS, jwk, body
}
func TestRejectsNone(t *testing.T) {
noneJWSBody := `
{
"header": {
"alg": "none",
"jwk": {
"kty": "RSA",
"n": "vrjT",
"e": "AQAB"
}
},
"payload": "aGkK",
"signature": "ghTIjrhiRl2pQ09vAkUUBbF5KziJdhzOTB-okM9SPRzU8Hyj0W1H5JA1Zoc-A-LuJGNAtYYHWqMw1SeZbT0l9FHcbMPeWDaJNkHS9jz5_g_Oyol8vcrWur2GDtB2Jgw6APtZKrbuGATbrF7g41Wijk6Kk9GXDoCnlfOQOhHhsrFFcWlCPLG-03TtKD6EBBoVBhmlp8DRLs7YguWRZ6jWNaEX-1WiRntBmhLqoqQFtvZxCBw_PRuaRw_RZBd1x2_BNYqEdOmVNC43UHMSJg3y_3yrPo905ur09aUTscf-C_m4Sa4M0FuDKn3bQ_pFrtz-aCCq6rcTIyxYpDqNvHMT2Q"
}
`
noneJWS, err := jose.ParseSigned(noneJWSBody)
if err != nil {
t.Fatal("Unable to parse noneJWS")
}
noneJWK := noneJWS.Signatures[0].Header.JSONWebKey
err = checkAlgorithm(noneJWK, noneJWS)
if err == nil {
t.Fatalf("checkAlgorithm did not reject JWS with alg: 'none'")
}
if err.Error() != "JWS signature header contains unsupported algorithm \"none\", expected one of RS256, ES256, ES384 or ES512" {
t.Fatalf("checkAlgorithm rejected JWS with alg: 'none', but for wrong reason: %#v", err)
}
}
func TestRejectsHS256(t *testing.T) {
hs256JWSBody := `
{
"header": {
"alg": "HS256",
"jwk": {
"kty": "RSA",
"n": "vrjT",
"e": "AQAB"
}
},
"payload": "aGkK",
"signature": "ghTIjrhiRl2pQ09vAkUUBbF5KziJdhzOTB-okM9SPRzU8Hyj0W1H5JA1Zoc-A-LuJGNAtYYHWqMw1SeZbT0l9FHcbMPeWDaJNkHS9jz5_g_Oyol8vcrWur2GDtB2Jgw6APtZKrbuGATbrF7g41Wijk6Kk9GXDoCnlfOQOhHhsrFFcWlCPLG-03TtKD6EBBoVBhmlp8DRLs7YguWRZ6jWNaEX-1WiRntBmhLqoqQFtvZxCBw_PRuaRw_RZBd1x2_BNYqEdOmVNC43UHMSJg3y_3yrPo905ur09aUTscf-C_m4Sa4M0FuDKn3bQ_pFrtz-aCCq6rcTIyxYpDqNvHMT2Q"
}
`
hs256JWS, err := jose.ParseSigned(hs256JWSBody)
if err != nil {
t.Fatal("Unable to parse hs256JWSBody")
}
hs256JWK := hs256JWS.Signatures[0].Header.JSONWebKey
err = checkAlgorithm(hs256JWK, hs256JWS)
if err == nil {
t.Fatalf("checkAlgorithm did not reject JWS with alg: 'HS256'")
}
expected := "JWS signature header contains unsupported algorithm \"HS256\", expected one of RS256, ES256, ES384 or ES512"
if err.Error() != expected {
t.Fatalf("checkAlgorithm rejected JWS with alg: 'none', but for wrong reason: got %q, wanted %q", err.Error(), expected)
}
}
func TestCheckAlgorithm(t *testing.T) {
testCases := []struct {
key jose.JSONWebKey
jws jose.JSONWebSignature
expectedErr string
}{
{
jose.JSONWebKey{},
jose.JSONWebSignature{
Signatures: []jose.Signature{
{
Header: jose.Header{
Algorithm: "HS256",
},
},
},
},
"JWS signature header contains unsupported algorithm \"HS256\", expected one of RS256, ES256, ES384 or ES512",
},
{
jose.JSONWebKey{
Key: &dsa.PublicKey{},
},
jose.JSONWebSignature{
Signatures: []jose.Signature{
{
Header: jose.Header{
Algorithm: "ES512",
},
},
},
},
"JWK contains unsupported key type (expected RSA, or ECDSA P-256, P-384, or P-521",
},
{
jose.JSONWebKey{
Algorithm: "RS256",
Key: &rsa.PublicKey{},
},
jose.JSONWebSignature{
Signatures: []jose.Signature{
{
Header: jose.Header{
Algorithm: "ES512",
},
},
},
},
"JWS signature header algorithm \"ES512\" does not match expected algorithm \"RS256\" for JWK",
},
{
jose.JSONWebKey{
Algorithm: "HS256",
Key: &rsa.PublicKey{},
},
jose.JSONWebSignature{
Signatures: []jose.Signature{
{
Header: jose.Header{
Algorithm: "RS256",
},
},
},
},
"JWK key header algorithm \"HS256\" does not match expected algorithm \"RS256\" for JWK",
},
}
for i, tc := range testCases {
err := checkAlgorithm(&tc.key, &tc.jws)
if tc.expectedErr != "" && err.Error() != tc.expectedErr {
t.Errorf("TestCheckAlgorithm %d: Expected %q, got %q", i, tc.expectedErr, err)
}
}
}
func TestCheckAlgorithmSuccess(t *testing.T) {
err := checkAlgorithm(&jose.JSONWebKey{
Algorithm: "RS256",
Key: &rsa.PublicKey{},
}, &jose.JSONWebSignature{
Signatures: []jose.Signature{
{
Header: jose.Header{
Algorithm: "RS256",
},
},
},
})
if err != nil {
t.Errorf("RS256 key: Expected nil error, got '%s'", err)
}
err = checkAlgorithm(&jose.JSONWebKey{
Key: &rsa.PublicKey{},
}, &jose.JSONWebSignature{
Signatures: []jose.Signature{
{
Header: jose.Header{
Algorithm: "RS256",
},
},
},
})
if err != nil {
t.Errorf("RS256 key: Expected nil error, got '%s'", err)
}
err = checkAlgorithm(&jose.JSONWebKey{
Algorithm: "ES256",
Key: &ecdsa.PublicKey{
Curve: elliptic.P256(),
},
}, &jose.JSONWebSignature{
Signatures: []jose.Signature{
{
Header: jose.Header{
Algorithm: "ES256",
},
},
},
})
if err != nil {
t.Errorf("ES256 key: Expected nil error, got '%s'", err)
}
err = checkAlgorithm(&jose.JSONWebKey{
Key: &ecdsa.PublicKey{
Curve: elliptic.P256(),
},
}, &jose.JSONWebSignature{
Signatures: []jose.Signature{
{
Header: jose.Header{
Algorithm: "ES256",
},
},
},
})
if err != nil {
t.Errorf("ES256 key: Expected nil error, got '%s'", err)
}
}
func TestValidPOSTRequest(t *testing.T) {
wfe, _ := setupWFE(t)
dummyContentLength := []string{"pretty long, idk, maybe a nibble or two?"}
testCases := []struct {
Name string
Headers map[string][]string
Body *string
HTTPStatus int
ProblemDetail string
ErrorStatType string
EnforceContentType bool
}{
// POST requests without a Content-Length should produce a problem
{
Name: "POST without a Content-Length header",
Headers: nil,
HTTPStatus: http.StatusLengthRequired,
ProblemDetail: "missing Content-Length header",
ErrorStatType: "ContentLengthRequired",
},
// POST requests with a Replay-Nonce header should produce a problem
{
Name: "POST with a Replay-Nonce HTTP header",
Headers: map[string][]string{
"Content-Length": dummyContentLength,
"Replay-Nonce": {"ima-misplaced-nonce"},
"Content-Type": {expectedJWSContentType},
},
HTTPStatus: http.StatusBadRequest,
ProblemDetail: "HTTP requests should NOT contain Replay-Nonce header. Use JWS nonce field",
ErrorStatType: "ReplayNonceOutsideJWS",
},
// POST requests without a body should produce a problem
{
Name: "POST with an empty POST body",
Headers: map[string][]string{
"Content-Length": dummyContentLength,
"Content-Type": {expectedJWSContentType},
},
HTTPStatus: http.StatusBadRequest,
ProblemDetail: "No body on POST",
ErrorStatType: "NoPOSTBody",
},
{
Name: "POST without a Content-Type header",
Headers: map[string][]string{
"Content-Length": dummyContentLength,
},
HTTPStatus: http.StatusUnsupportedMediaType,
ProblemDetail: fmt.Sprintf(
"No Content-Type header on POST. Content-Type must be %q",
expectedJWSContentType),
ErrorStatType: "NoContentType",
EnforceContentType: true,
},
{
Name: "POST with an invalid Content-Type header",
Headers: map[string][]string{
"Content-Length": dummyContentLength,
"Content-Type": {"fresh.and.rare"},
},
HTTPStatus: http.StatusUnsupportedMediaType,
ProblemDetail: fmt.Sprintf(
"Invalid Content-Type header on POST. Content-Type must be %q",
expectedJWSContentType),
ErrorStatType: "WrongContentType",
EnforceContentType: true,
},
}
for _, tc := range testCases {
input := &http.Request{
Method: "POST",
URL: mustParseURL("/"),
Header: tc.Headers,
}
t.Run(tc.Name, func(t *testing.T) {
prob := wfe.validPOSTRequest(input)
test.Assert(t, prob != nil, "No error returned for invalid POST")
test.AssertEquals(t, prob.Type, probs.MalformedProblem)
test.AssertEquals(t, prob.HTTPStatus, tc.HTTPStatus)
test.AssertEquals(t, prob.Detail, tc.ProblemDetail)
test.AssertMetricWithLabelsEquals(
t, wfe.stats.httpErrorCount, prometheus.Labels{"type": tc.ErrorStatType}, 1)
})
}
}
func TestEnforceJWSAuthType(t *testing.T) {
wfe, _ := setupWFE(t)
testKeyIDJWS, _, _ := signRequestKeyID(t, 1, nil, "", "", wfe.nonceService)
testEmbeddedJWS, _, _ := signRequestEmbed(t, nil, "", "", wfe.nonceService)
// A hand crafted JWS that has both a Key ID and an embedded JWK
conflictJWSBody := `
{
"header": {
"alg": "RS256",
"jwk": {
"e": "AQAB",
"kty": "RSA",
"n": "ppbqGaMFnnq9TeMUryR6WW4Lr5WMgp46KlBXZkNaGDNQoifWt6LheeR5j9MgYkIFU7Z8Jw5-bpJzuBeEVwb-yHGh4Umwo_qKtvAJd44iLjBmhBSxq-OSe6P5hX1LGCByEZlYCyoy98zOtio8VK_XyS5VoOXqchCzBXYf32ksVUTrtH1jSlamKHGz0Q0pRKIsA2fLqkE_MD3jP6wUDD6ExMw_tKYLx21lGcK41WSrRpDH-kcZo1QdgCy2ceNzaliBX1eHmKG0-H8tY4tPQudk-oHQmWTdvUIiHO6gSKMGDZNWv6bq74VTCsRfUEAkuWhqUhgRSGzlvlZ24wjHv5Qdlw"
}
},
"protected": "eyJub25jZSI6ICJibTl1WTJVIiwgInVybCI6ICJodHRwOi8vbG9jYWxob3N0L3Rlc3QiLCAia2lkIjogInRlc3RrZXkifQ",
"payload": "Zm9v",
"signature": "ghTIjrhiRl2pQ09vAkUUBbF5KziJdhzOTB-okM9SPRzU8Hyj0W1H5JA1Zoc-A-LuJGNAtYYHWqMw1SeZbT0l9FHcbMPeWDaJNkHS9jz5_g_Oyol8vcrWur2GDtB2Jgw6APtZKrbuGATbrF7g41Wijk6Kk9GXDoCnlfOQOhHhsrFFcWlCPLG-03TtKD6EBBoVBhmlp8DRLs7YguWRZ6jWNaEX-1WiRntBmhLqoqQFtvZxCBw_PRuaRw_RZBd1x2_BNYqEdOmVNC43UHMSJg3y_3yrPo905ur09aUTscf-C_m4Sa4M0FuDKn3bQ_pFrtz-aCCq6rcTIyxYpDqNvHMT2Q"
}
`
conflictJWS, err := jose.ParseSigned(conflictJWSBody)
if err != nil {
t.Fatal("Unable to parse conflict JWS")
}
testCases := []struct {
Name string
JWS *jose.JSONWebSignature
ExpectedAuthType jwsAuthType
ExpectedResult *probs.ProblemDetails
ErrorStatType string
}{
{
Name: "Key ID and embedded JWS",
JWS: conflictJWS,
ExpectedAuthType: invalidAuthType,
ExpectedResult: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "jwk and kid header fields are mutually exclusive",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSAuthTypeInvalid",
},
{
Name: "Key ID when expected is embedded JWK",
JWS: testKeyIDJWS,
ExpectedAuthType: embeddedJWK,
ExpectedResult: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "No embedded JWK in JWS header",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSAuthTypeWrong",
},
{
Name: "Embedded JWK when expected is Key ID",
JWS: testEmbeddedJWS,
ExpectedAuthType: embeddedKeyID,
ExpectedResult: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "No Key ID in JWS header",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSAuthTypeWrong",
},
{
Name: "Key ID when expected is KeyID",
JWS: testKeyIDJWS,
ExpectedAuthType: embeddedKeyID,
ExpectedResult: nil,
},
{
Name: "Embedded JWK when expected is embedded JWK",
JWS: testEmbeddedJWS,
ExpectedAuthType: embeddedJWK,
ExpectedResult: nil,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
wfe.stats.joseErrorCount.Reset()
prob := wfe.enforceJWSAuthType(tc.JWS, tc.ExpectedAuthType)
if tc.ExpectedResult == nil && prob != nil {
t.Fatalf("Expected nil result, got %#v", prob)
} else {
test.AssertMarshaledEquals(t, prob, tc.ExpectedResult)
}
if tc.ErrorStatType != "" {
test.AssertMetricWithLabelsEquals(
t, wfe.stats.joseErrorCount, prometheus.Labels{"type": tc.ErrorStatType}, 1)
}
})
}
}
type badNonceProvider struct {
}
func (badNonceProvider) Nonce() (string, error) {
return "im-a-nonce", nil
}
func TestValidNonce(t *testing.T) {
wfe, _ := setupWFE(t)
// signRequestEmbed with a `nil` nonce.NonceService will result in the
// JWS not having a protected nonce header.
missingNonceJWS, _, _ := signRequestEmbed(t, nil, "", "", nil)
// signRequestEmbed with a badNonceProvider will result in the JWS
// having an invalid nonce
invalidNonceJWS, _, _ := signRequestEmbed(t, nil, "", "", badNonceProvider{})
goodJWS, _, _ := signRequestEmbed(t, nil, "", "", wfe.nonceService)
testCases := []struct {
Name string
JWS *jose.JSONWebSignature
ExpectedResult *probs.ProblemDetails
ErrorStatType string
}{
{
Name: "No nonce in JWS",
JWS: missingNonceJWS,
ExpectedResult: &probs.ProblemDetails{
Type: probs.BadNonceProblem,
Detail: "JWS has no anti-replay nonce",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSMissingNonce",
},
{
Name: "Invalid nonce in JWS",
JWS: invalidNonceJWS,
ExpectedResult: &probs.ProblemDetails{
Type: probs.BadNonceProblem,
Detail: "JWS has an invalid anti-replay nonce: \"im-a-nonce\"",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSInvalidNonce",
},
{
Name: "Valid nonce in JWS",
JWS: goodJWS,
ExpectedResult: nil,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
wfe.stats.joseErrorCount.Reset()
prob := wfe.validNonce(context.Background(), tc.JWS)
if tc.ExpectedResult == nil && prob != nil {
t.Fatalf("Expected nil result, got %#v", prob)
} else {
test.AssertMarshaledEquals(t, prob, tc.ExpectedResult)
}
if tc.ErrorStatType != "" {
test.AssertMetricWithLabelsEquals(
t, wfe.stats.joseErrorCount, prometheus.Labels{"type": tc.ErrorStatType}, 1)
}
})
}
}
func signExtraHeaders(
t *testing.T,
headers map[jose.HeaderKey]interface{},
nonceService jose.NonceSource) (*jose.JSONWebSignature, string) {
privateKey := loadKey(t, []byte(test1KeyPrivatePEM))
signerKey := jose.SigningKey{
Key: privateKey,
Algorithm: sigAlgForKey(t, privateKey.Public()),
}
opts := &jose.SignerOptions{
NonceSource: nonceService,
EmbedJWK: true,
ExtraHeaders: headers,
}
signer, err := jose.NewSigner(signerKey, opts)
test.AssertNotError(t, err, "Failed to make signer")
jws, err := signer.Sign([]byte(""))
test.AssertNotError(t, err, "Failed to sign req")
body := jws.FullSerialize()
parsedJWS, err := jose.ParseSigned(body)
test.AssertNotError(t, err, "Failed to parse generated JWS")
return parsedJWS, body
}
func TestValidPOSTURL(t *testing.T) {
wfe, _ := setupWFE(t)
// A JWS and HTTP request with no extra headers
noHeadersJWS, noHeadersJWSBody := signExtraHeaders(t, nil, wfe.nonceService)
noHeadersRequest := makePostRequestWithPath("test-path", noHeadersJWSBody)
// A JWS and HTTP request with extra headers, but no "url" extra header
noURLHeaders := map[jose.HeaderKey]interface{}{
"nifty": "swell",
}
noURLHeaderJWS, noURLHeaderJWSBody := signExtraHeaders(t, noURLHeaders, wfe.nonceService)
noURLHeaderRequest := makePostRequestWithPath("test-path", noURLHeaderJWSBody)
// A JWS and HTTP request with a mismatched HTTP URL to JWS "url" header
wrongURLHeaders := map[jose.HeaderKey]interface{}{
"url": "foobar",
}
wrongURLHeaderJWS, wrongURLHeaderJWSBody := signExtraHeaders(t, wrongURLHeaders, wfe.nonceService)
wrongURLHeaderRequest := makePostRequestWithPath("test-path", wrongURLHeaderJWSBody)
correctURLHeaderJWS, _, correctURLHeaderJWSBody := signRequestEmbed(t, nil, "http://localhost/test-path", "", wfe.nonceService)
correctURLHeaderRequest := makePostRequestWithPath("test-path", correctURLHeaderJWSBody)
testCases := []struct {
Name string
JWS *jose.JSONWebSignature
Request *http.Request
ExpectedResult *probs.ProblemDetails
ErrorStatType string
}{
{
Name: "No extra headers in JWS",
JWS: noHeadersJWS,
Request: noHeadersRequest,
ExpectedResult: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "JWS header parameter 'url' required",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSNoExtraHeaders",
},
{
Name: "No URL header in JWS",
JWS: noURLHeaderJWS,
Request: noURLHeaderRequest,
ExpectedResult: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "JWS header parameter 'url' required",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSMissingURL",
},
{
Name: "Wrong URL header in JWS",
JWS: wrongURLHeaderJWS,
Request: wrongURLHeaderRequest,
ExpectedResult: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "JWS header parameter 'url' incorrect. Expected \"http://localhost/test-path\" got \"foobar\"",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSMismatchedURL",
},
{
Name: "Correct URL header in JWS",
JWS: correctURLHeaderJWS,
Request: correctURLHeaderRequest,
ExpectedResult: nil,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
tc.Request.Header.Add("Content-Type", expectedJWSContentType)
wfe.stats.joseErrorCount.Reset()
prob := wfe.validPOSTURL(tc.Request, tc.JWS)
if tc.ExpectedResult == nil && prob != nil {
t.Fatalf("Expected nil result, got %#v", prob)
} else {
test.AssertMarshaledEquals(t, prob, tc.ExpectedResult)
}
if tc.ErrorStatType != "" {
test.AssertMetricWithLabelsEquals(
t, wfe.stats.joseErrorCount, prometheus.Labels{"type": tc.ErrorStatType}, 1)
}
})
}
}
func multiSigJWS(t *testing.T, nonceService jose.NonceSource) (*jose.JSONWebSignature, string) {
privateKeyA := loadKey(t, []byte(test1KeyPrivatePEM))
privateKeyB := loadKey(t, []byte(test2KeyPrivatePEM))
signerKeyA := jose.SigningKey{
Key: privateKeyA,
Algorithm: sigAlgForKey(t, privateKeyA.Public()),
}
signerKeyB := jose.SigningKey{
Key: privateKeyB,
Algorithm: sigAlgForKey(t, privateKeyB.Public()),
}
opts := &jose.SignerOptions{
NonceSource: nonceService,
EmbedJWK: true,
}
signer, err := jose.NewMultiSigner([]jose.SigningKey{signerKeyA, signerKeyB}, opts)
test.AssertNotError(t, err, "Failed to make multi signer")
jws, err := signer.Sign([]byte(""))
test.AssertNotError(t, err, "Failed to sign req")
body := jws.FullSerialize()
parsedJWS, err := jose.ParseSigned(body)
test.AssertNotError(t, err, "Failed to parse generated JWS")
return parsedJWS, body
}
func TestParseJWSRequest(t *testing.T) {
wfe, _ := setupWFE(t)
_, tooManySigsJWSBody := multiSigJWS(t, wfe.nonceService)
_, _, validJWSBody := signRequestEmbed(t, nil, "http://localhost/test-path", "", wfe.nonceService)
validJWSRequest := makePostRequestWithPath("test-path", validJWSBody)
missingSigsJWSBody := `{"payload":"Zm9x","protected":"eyJhbGciOiJSUzI1NiIsImp3ayI6eyJrdHkiOiJSU0EiLCJuIjoicW5BUkxyVDdYejRnUmNLeUxkeWRtQ3ItZXk5T3VQSW1YNFg0MHRoazNvbjI2RmtNem5SM2ZSanM2NmVMSzdtbVBjQlo2dU9Kc2VVUlU2d0FhWk5tZW1vWXgxZE12cXZXV0l5aVFsZUhTRDdROHZCcmhSNnVJb080akF6SlpSLUNoelp1U0R0N2lITi0zeFVWc3B1NVhHd1hVX01WSlpzaFR3cDRUYUZ4NWVsSElUX09iblR2VE9VM1hoaXNoMDdBYmdaS21Xc1ZiWGg1cy1DcklpY1U0T2V4SlBndW5XWl9ZSkp1ZU9LbVR2bkxsVFY0TXpLUjJvWmxCS1oyN1MwLVNmZFZfUUR4X3lkbGU1b01BeUtWdGxBVjM1Y3lQTUlzWU53Z1VHQkNkWV8yVXppNWVYMGxUYzdNUFJ3ejZxUjFraXAtaTU5VmNHY1VRZ3FIVjZGeXF3IiwiZSI6IkFRQUIifSwia2lkIjoiIiwibm9uY2UiOiJyNHpuenZQQUVwMDlDN1JwZUtYVHhvNkx3SGwxZVBVdmpGeXhOSE1hQnVvIiwidXJsIjoiaHR0cDovL2xvY2FsaG9zdC9hY21lL25ldy1yZWcifQ"}`
missingSigsJWSRequest := makePostRequestWithPath("test-path", missingSigsJWSBody)
unprotectedHeadersJWSBody := `
{
"header": {
"alg": "RS256",
"kid": "unprotected key id"
},
"protected": "eyJub25jZSI6ICJibTl1WTJVIiwgInVybCI6ICJodHRwOi8vbG9jYWxob3N0L3Rlc3QiLCAia2lkIjogInRlc3RrZXkifQ",
"payload": "Zm9v",
"signature": "PKWWclRsiHF4bm-nmpxDez6Y_3Mdtu263YeYklbGYt1EiMOLiKY_dr_EqhUUKAKEWysFLO-hQLXVU7kVkHeYWQFFOA18oFgcZgkSF2Pr3DNZrVj9e2gl0eZ2i2jk6X5GYPt1lIfok_DrL92wrxEKGcrmxqXXGm0JgP6Al2VGapKZK2HaYbCHoGvtzNmzUX9rC21sKewq5CquJRvTmvQp5bmU7Q9KeafGibFr0jl6IA3W5LBGgf6xftuUtEVEbKmKaKtaG7tXsQH1mIVOPUZZoLWz9sWJSFLmV0QSXm3ZHV0DrOhLfcADbOCoQBMeGdseBQZuUO541A3BEKGv2Aikjw"
}
`
wrongSignaturesFieldJWSBody := `
{
"protected": "eyJub25jZSI6ICJibTl1WTJVIiwgInVybCI6ICJodHRwOi8vbG9jYWxob3N0L3Rlc3QiLCAia2lkIjogInRlc3RrZXkifQ",
"payload": "Zm9v",
"signatures": ["PKWWclRsiHF4bm-nmpxDez6Y_3Mdtu263YeYklbGYt1EiMOLiKY_dr_EqhUUKAKEWysFLO-hQLXVU7kVkHeYWQFFOA18oFgcZgkSF2Pr3DNZrVj9e2gl0eZ2i2jk6X5GYPt1lIfok_DrL92wrxEKGcrmxqXXGm0JgP6Al2VGapKZK2HaYbCHoGvtzNmzUX9rC21sKewq5CquJRvTmvQp5bmU7Q9KeafGibFr0jl6IA3W5LBGgf6xftuUtEVEbKmKaKtaG7tXsQH1mIVOPUZZoLWz9sWJSFLmV0QSXm3ZHV0DrOhLfcADbOCoQBMeGdseBQZuUO541A3BEKGv2Aikjw"]
}
`
testCases := []struct {
Name string
Request *http.Request
ExpectedProblem *probs.ProblemDetails
ErrorStatType string
}{
{
Name: "Invalid POST request",
// No Content-Length, something that validPOSTRequest should be flagging
Request: &http.Request{
Method: "POST",
URL: mustParseURL("/"),
},
ExpectedProblem: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "missing Content-Length header",
HTTPStatus: http.StatusLengthRequired,
},
},
{
Name: "Invalid JWS in POST body",
Request: makePostRequestWithPath("test-path", `{`),
ExpectedProblem: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "Parse error reading JWS",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSUnmarshalFailed",
},
{
Name: "Too few signatures in JWS",
Request: missingSigsJWSRequest,
ExpectedProblem: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "POST JWS not signed",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSEmptySignature",
},
{
Name: "Too many signatures in JWS",
Request: makePostRequestWithPath("test-path", tooManySigsJWSBody),
ExpectedProblem: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "JWS \"signatures\" field not allowed. Only the \"signature\" field should contain a signature",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSMultiSig",
},
{
Name: "Unprotected JWS headers",
Request: makePostRequestWithPath("test-path", unprotectedHeadersJWSBody),
ExpectedProblem: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "JWS \"header\" field not allowed. All headers must be in \"protected\" field",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSUnprotectedHeaders",
},
{
Name: "Unsupported signatures field in JWS",
Request: makePostRequestWithPath("test-path", wrongSignaturesFieldJWSBody),
ExpectedProblem: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "JWS \"signatures\" field not allowed. Only the \"signature\" field should contain a signature",
HTTPStatus: http.StatusBadRequest,
},
ErrorStatType: "JWSMultiSig",
},
{
Name: "Valid JWS in POST request",
Request: validJWSRequest,
ExpectedProblem: nil,
},
{
Name: "POST body too large",
Request: makePostRequestWithPath("test-path",
fmt.Sprintf(`{"a":"%s"}`, strings.Repeat("a", 50000))),
ExpectedProblem: &probs.ProblemDetails{
Type: probs.UnauthorizedProblem,
Detail: "request body too large",
HTTPStatus: http.StatusForbidden,
},
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
wfe.stats.joseErrorCount.Reset()
_, prob := wfe.parseJWSRequest(tc.Request)
if tc.ExpectedProblem == nil && prob != nil {
t.Fatalf("Expected nil problem, got %#v\n", prob)
} else {
test.AssertMarshaledEquals(t, prob, tc.ExpectedProblem)
}
if tc.ErrorStatType != "" {
test.AssertMetricWithLabelsEquals(
t, wfe.stats.joseErrorCount, prometheus.Labels{"type": tc.ErrorStatType}, 1)
}
})
}
}
func TestExtractJWK(t *testing.T) {
wfe, _ := setupWFE(t)
keyIDJWS, _, _ := signRequestKeyID(t, 1, nil, "", "", wfe.nonceService)
goodJWS, goodJWK, _ := signRequestEmbed(t, nil, "", "", wfe.nonceService)
testCases := []struct {
Name string
JWS *jose.JSONWebSignature
ExpectedKey *jose.JSONWebKey
ExpectedProblem *probs.ProblemDetails
}{
{
Name: "JWS with wrong auth type (Key ID vs embedded JWK)",
JWS: keyIDJWS,
ExpectedProblem: &probs.ProblemDetails{
Type: probs.MalformedProblem,
Detail: "No embedded JWK in JWS header",
HTTPStatus: http.StatusBadRequest,
},
},
{
Name: "Valid JWS with embedded JWK",
JWS: goodJWS,
ExpectedKey: goodJWK,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
jwk, prob := wfe.extractJWK(tc.JWS)
if tc.ExpectedProblem == nil && prob != nil {
t.Fatalf("Expected nil problem, got %#v\n", prob)
} else if tc.ExpectedProblem == nil {
test.AssertMarshaledEquals(t, jwk, tc.ExpectedKey)
} else {
test.AssertMarshaledEquals(t, prob, tc.ExpectedProblem)
}
})
}
}
func signRequestSpecifyKeyID(t *testing.T, keyID string, nonceService jose.NonceSource) (*jose.JSONWebSignature, string) {
privateKey := loadKey(t, []byte(test1KeyPrivatePEM))
if keyID == "" {
keyID = "this is an invalid non-numeric key ID"
}
jwk := &jose.JSONWebKey{
Key: privateKey,
Algorithm: "RSA",
KeyID: keyID,
}
signerKey := jose.SigningKey{
Key: jwk,
Algorithm: jose.RS256,
}
opts := &jose.SignerOptions{
NonceSource: nonceService,
ExtraHeaders: map[jose.HeaderKey]interface{}{
"url": "http://localhost",
},
}
signer, err := jose.NewSigner(signerKey, opts)
test.AssertNotError(t, err, "Failed to make signer")
jws, err := signer.Sign([]byte(""))
test.AssertNotError(t, err, "Failed to sign req")
body := jws.FullSerialize()
parsedJWS, err := jose.ParseSigned(body)
test.AssertNotError(t, err, "Failed to parse generated JWS")
return parsedJWS, body
}
func TestLookupJWK(t *testing.T) {
wfe, _ := setupWFE(t)