-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathwfe.go
More file actions
3194 lines (2816 loc) · 100 KB
/
wfe.go
File metadata and controls
3194 lines (2816 loc) · 100 KB
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 wfe
import (
"bytes"
"context"
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"log"
"math/big"
"math/rand"
"net"
"net/http"
"net/mail"
"net/url"
"os"
"slices"
"sort"
"strconv"
"strings"
"time"
"unicode"
"github.com/go-jose/go-jose/v4"
"github.com/letsencrypt/pebble/v2/acme"
"github.com/letsencrypt/pebble/v2/ca"
"github.com/letsencrypt/pebble/v2/core"
"github.com/letsencrypt/pebble/v2/db"
"github.com/letsencrypt/pebble/v2/va"
)
const (
// Note: We deliberately pick endpoint paths that differ from Boulder to
// exercise clients processing of the /directory response
// We export the DirectoryPath so that the pebble binary can reference it
DirectoryPath = "/dir"
noncePath = "/nonce-plz"
newAccountPath = "/sign-me-up"
acctPath = "/my-account/"
newOrderPath = "/order-plz"
orderPath = "/my-order/"
orderFinalizePath = "/finalize-order/"
authzPath = "/authZ/"
challengePath = "/chalZ/"
certPath = "/certZ/"
revokeCertPath = "/revoke-cert"
keyRolloverPath = "/rollover-account-key"
ordersPath = "/list-orderz/"
// Draft or likely-to-change paths
renewalInfoPath = "/draft-ietf-acme-ari-03/renewalInfo/"
// These entrypoints are not a part of the standard ACME endpoints,
// and are exposed by Pebble as an integration test tool. We export
// RootCertPath so that the pebble binary can reference it.
RootCertPath = "/roots/"
rootKeyPath = "/root-keys/"
intermediateCertPath = "/intermediates/"
intermediateKeyPath = "/intermediate-keys/"
certStatusBySerial = "/cert-status-by-serial/"
// Post certificate PEM and desired literal response for renewal info
// (the renewal info response is not validated so may be intentionally
// malformed).
setRenewalInfoPath = "/set-renewal-info/"
// How long do pending authorizations last before expiring?
pendingAuthzExpire = time.Hour
// How many contacts is an account allowed to have?
maxContactsPerAcct = 2
// badNonceEnvVar defines the environment variable name used to provide
// a percentage value for how often good nonces should be rejected as if they
// were bad. This can be used to exercise client nonce handling/retries.
// To have the WFE not reject any good nonces, run Pebble like:
// PEBBLE_WFE_NONCEREJECT=0 pebble
// To have the WFE reject 15% of good nonces, run Pebble like:
// PEBBLE_WFE_NONCEREJECT=15 pebble
badNonceEnvVar = "PEBBLE_WFE_NONCEREJECT"
// By default when no PEBBLE_WFE_NONCEREJECT is set, what percentage of good
// nonces are rejected?
defaultNonceReject = 5
// POST requests with a JWS body must have the following Content-Type header
expectedJWSContentType = "application/jose+json"
// RFC 1034 says DNS labels have a max of 63 octets, and names have a max of 255
// octets: https://tools.ietf.org/html/rfc1035#page-10. Since two of those octets
// are taken up by the leading length byte and the trailing root period the actual
// max length becomes 253.
maxDNSIdentifierLength = 253
// Invalid revocation reason codes.
// The full list of codes can be found in Section 8.5.3.1 of ITU-T X.509
// http://www.itu.int/rec/T-REC-X.509-201210-I/en
unusedRevocationReason = 7
aACompromiseRevocationReason = 10
// authzReuseEnvVar defines an environment variable name used to provide a
// percentage value for how often Pebble should try to reuse valid authorizations
// for each identifier in an order. The percentage is independent of whether a
// valid authorization exists or not for each identifier in an order.
authzReuseEnvVar = "PEBBLE_AUTHZREUSE"
// jitEnvVar defines an environment variable name used to wether if wfe
// should ask VA if there is valid dns-persist-01 record at order creation time
jitEnvVar = "PEBBLE_WFE_JITVALIDATION"
// The default value when PEBBLE_WFE_AUTHZREUSE is not set, how often to try
// and reuse valid authorizations.
defaultAuthzReuse = 50
// ordersPerPageEnvVar defines the environment variable name used to provide
// the number of orders to show per page. To have the WFE show 15 orders per
// page, run Pebble like:
// PEBBLE_WFE_ORDERS_PER_PAGE=15 pebble
ordersPerPageEnvVar = "PEBBLE_WFE_ORDERS_PER_PAGE"
// The default number of orders enumerated per page
defaultOrdersPerPage = 3
)
var goodSignatureAlgorithms = map[x509.SignatureAlgorithm]bool{
x509.SHA256WithRSA: true,
x509.SHA384WithRSA: true,
x509.SHA512WithRSA: true,
x509.ECDSAWithSHA256: true,
x509.ECDSAWithSHA384: true,
x509.ECDSAWithSHA512: true,
}
// newAccountRequest is the ACME account information submitted by the client
type newAccountRequest struct {
Contact []string `json:"contact"`
ToSAgreed bool `json:"termsOfServiceAgreed"`
OnlyReturnExisting bool `json:"onlyReturnExisting"`
ExternalAccountBinding *acme.JSONSigned `json:"externalAccountBinding,omitempty"`
}
type wfeHandlerFunc func(context.Context, http.ResponseWriter, *http.Request)
func (f wfeHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := context.TODO()
f(ctx, w, r)
}
type wfeHandler interface {
ServeHTTP(w http.ResponseWriter, r *http.Request)
}
type topHandler struct {
wfe wfeHandler
}
func (th *topHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
th.wfe.ServeHTTP(w, r)
}
type WebFrontEndImpl struct {
log *log.Logger
db *db.MemoryStore
nonce *nonceMap
nonceErrPercent int
authzReusePercent int
ordersPerPage int
va *va.VAImpl
ca *ca.CAImpl
caaIdentities []string
strict bool
requireEAB bool
jitValidation bool
retryAfterAuthz int
retryAfterOrder int
}
const ToSURL = "data:text/plain,Do%20what%20thou%20wilt"
func New(
log *log.Logger,
db *db.MemoryStore,
va *va.VAImpl,
ca *ca.CAImpl,
caaIdentities []string,
strict, requireEAB bool, retryAfterAuthz int, retryAfterOrder int,
) WebFrontEndImpl {
// Read the % of good nonces that should be rejected as bad nonces from the
// environment
nonceErrPercentVal := os.Getenv(badNonceEnvVar)
var nonceErrPercent int
// Parse the env var value as a base 10 int - if there isn't an error, use it
// as the wfe nonceErrPercent
if val, err := strconv.ParseInt(nonceErrPercentVal, 10, 0); err == nil {
nonceErrPercent = int(val)
} else {
// Otherwise just use the default
nonceErrPercent = defaultNonceReject
}
// If the value is out of the range just clip it sensibly
if nonceErrPercent < 0 {
nonceErrPercent = 0
} else if nonceErrPercent > 100 {
nonceErrPercent = 99
}
log.Printf("Configured to reject %d%% of good nonces", nonceErrPercent)
// Get authz reuse percent from the environment
authzReusePercent := defaultAuthzReuse
if val, err := strconv.ParseInt(os.Getenv(authzReuseEnvVar), 10, 0); err == nil &&
val >= 0 && val <= 100 {
authzReusePercent = int(val)
}
log.Printf("Configured to attempt authz reuse for each identifier %d%% of the time",
authzReusePercent)
jitvalidation := false
jitvar := os.Getenv(jitEnvVar)
switch jitvar {
case "1", "true", "True", "TRUE":
jitvalidation = true
log.Printf("enabling JIT validation requests. WFE will request dns-persist-01 lookup at order creation time")
}
// Read the number of orders per page that should be returned.
ordersPerPageVal := os.Getenv(ordersPerPageEnvVar)
var ordersPerPage int
// Parse the env var value as a base 10 int - if there isn't an error, use it
// as the wfe nonceErrPercent
if val, err := strconv.ParseInt(ordersPerPageVal, 10, 0); err == nil && val > 0 {
ordersPerPage = int(val)
} else {
// Otherwise just use the default
ordersPerPage = defaultOrdersPerPage
}
log.Printf("Configured to show %d orders per page", ordersPerPage)
return WebFrontEndImpl{
log: log,
db: db,
nonce: newNonceMap(),
nonceErrPercent: nonceErrPercent,
authzReusePercent: authzReusePercent,
ordersPerPage: ordersPerPage,
va: va,
ca: ca,
jitValidation: jitvalidation,
strict: strict,
requireEAB: requireEAB,
retryAfterAuthz: retryAfterAuthz,
retryAfterOrder: retryAfterOrder,
caaIdentities: caaIdentities,
}
}
func (wfe *WebFrontEndImpl) HandleFunc(
mux *http.ServeMux,
pattern string,
handler wfeHandlerFunc,
methods ...string,
) {
methodsMap := make(map[string]bool)
for _, m := range methods {
methodsMap[m] = true
}
if methodsMap[http.MethodGet] && !methodsMap[http.MethodHead] {
// Allow HEAD for any resource that allows GET
methods = append(methods, http.MethodHead)
methodsMap[http.MethodHead] = true
}
methodsStr := strings.Join(methods, ", ")
defaultHandler := http.StripPrefix(pattern,
&topHandler{
wfe: wfeHandlerFunc(func(ctx context.Context, response http.ResponseWriter, request *http.Request) {
// Process CORS as necessary. If it's a CORS preflight, no further processing may occur.
if wfe.processCORS(request, response, methodsMap) {
return
}
// Reject all requests that do not include a User-Agent, which RFC 8555
// Section 6.1 requires all clients to supply in all requests.
if len(request.UserAgent()) == 0 {
wfe.sendError(acme.MalformedProblem("All requests MUST include a User-Agent header"), response)
return
}
// Modern ACME only sends a Replay-Nonce in responses to GET/HEAD
// requests to the dedicated newNonce endpoint, or in replies to POST
// requests that consumed a nonce.
if request.Method == http.MethodPost || pattern == noncePath {
response.Header().Set("Replay-Nonce", wfe.nonce.createNonce())
}
// Per section 7.1 "Resources":
// The "index" link relation is present on all resources other than the
// directory and indicates the URL of the directory.
if pattern != DirectoryPath {
directoryURL := wfe.relativeEndpoint(request, DirectoryPath)
response.Header().Add("Link", link(directoryURL, "index"))
}
addNoCacheHeader(response)
if !methodsMap[request.Method] {
response.Header().Set("Allow", methodsStr)
wfe.sendError(acme.MethodNotAllowed(), response)
return
}
wfe.log.Printf("%s %s -> calling handler()\n", request.Method, pattern)
// TODO(@cpu): Configurable request timeout
timeout := 1 * time.Minute
ctx, cancel := context.WithTimeout(ctx, timeout)
handler(ctx, response, request)
cancel()
},
),
})
mux.Handle(pattern, defaultHandler)
}
// processCORS reads and writes all necessary request and response headers in order to
// enable use by CORS-aware user agents. If the request is a CORS preflight request, the
// function returns true, in which case no further data may be written to the response.
func (wfe *WebFrontEndImpl) processCORS(request *http.Request, response http.ResponseWriter,
allowedMethodsMap map[string]bool,
) bool {
// 6.1.1, 6.2.1. No Origin header means CORS is not relevant.
// 6.1.2, 6.2.2. Origin's value is not processed because it always matches.
if request.Header.Get("Origin") == "" {
return false
}
// 6.2. Request is a CORS preflight
if request.Method == http.MethodOptions {
// 6.2.3, 6.2.5. -Request-Method must be present and must be a match for one of the allowed methods
method := request.Header.Get("Access-Control-Request-Method")
if _, allowed := allowedMethodsMap[method]; method == "" || !allowed {
return false
}
// 6.2.4, 6.2.6. -Request-Headers i not processed because it always matches.
// 6.2.7. Send -Allow-Origin, without -Allow-Credentials support.
response.Header().Set("Access-Control-Allow-Origin", "*")
// 6.2.8. Send -Max-Age.
response.Header().Set("Access-Control-Max-Age", "5")
// 6.2.9. -Allow-Methods is not sent because ACME only uses simple methods.
// 6.2.10. -Allow-Headers required for "Content-Type: application/jose+json"
response.Header().Set("Access-Control-Allow-Headers", "Content-Type")
// Terminate the request
response.WriteHeader(http.StatusNoContent)
return true
}
// 6.1. Otherwise, request is a CORS simple or actual request.
// 6.1.3. Send -Allow-Origin, without Allow-Credentials support.
response.Header().Set("Access-Control-Allow-Origin", "*")
// 6.1.4. Send -Expose-Headers for the response headers ACME uses.
response.Header().Set("Access-Control-Expose-Headers", "Link, Replay-Nonce, Location")
// Continue processing the request
return false
}
func (wfe *WebFrontEndImpl) HandleManagementFunc(
mux *http.ServeMux,
pattern string,
handler wfeHandlerFunc,
) {
mux.Handle(pattern, http.StripPrefix(pattern, handler))
}
func (wfe *WebFrontEndImpl) sendError(prob *acme.ProblemDetails, response http.ResponseWriter) {
problemDoc, err := marshalIndent(prob)
if err != nil {
problemDoc = []byte("{\"detail\": \"Problem marshaling error message.\"}")
}
response.Header().Set("Content-Type", "application/problem+json; charset=utf-8")
response.WriteHeader(prob.HTTPStatus)
_, _ = response.Write(problemDoc)
}
type (
certGetter func(no int) *core.Certificate
keyGetter func(no int) *rsa.PrivateKey
)
func (wfe *WebFrontEndImpl) handleCert(
certGet certGetter,
relPath string) func(
ctx context.Context,
response http.ResponseWriter,
request *http.Request) {
return func(_ context.Context, response http.ResponseWriter, request *http.Request) {
// Check for parameter
no, err := strconv.Atoi(request.URL.Path)
if err != nil {
response.WriteHeader(http.StatusNotFound)
return
}
// Get hold of root certificate
cert := certGet(no)
if cert == nil {
response.WriteHeader(http.StatusNotFound)
return
}
// Add links to alternate roots
basePath := wfe.relativeEndpoint(request, relPath)
for i := 0; i < wfe.ca.GetNumberOfRootCerts(); i++ {
if no == i {
continue
}
path := fmt.Sprintf("%s%d", basePath, i)
response.Header().Add("Link", link(path, "alternate"))
}
// Write main response
response.Header().Set("Content-Type", "application/pem-certificate-chain; charset=utf-8")
response.WriteHeader(http.StatusOK)
_, _ = response.Write(cert.PEM())
}
}
func (wfe *WebFrontEndImpl) handleKey(
keyGet keyGetter,
relPath string) func(
ctx context.Context,
response http.ResponseWriter,
request *http.Request) {
return func(_ context.Context, response http.ResponseWriter, request *http.Request) {
// Check for parameter
no, err := strconv.Atoi(request.URL.Path)
if err != nil {
response.WriteHeader(http.StatusNotFound)
return
}
// Get hold of root certificate's key
key := keyGet(no)
if key == nil {
response.WriteHeader(http.StatusNotFound)
return
}
// Add links to alternate root keys
basePath := wfe.relativeEndpoint(request, relPath)
for i := 0; i < wfe.ca.GetNumberOfRootCerts(); i++ {
if no == i {
continue
}
path := fmt.Sprintf("%s%d", basePath, i)
response.Header().Add("Link", link(path, "alternate"))
}
// Write main response
var buf bytes.Buffer
err = pem.Encode(&buf, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
})
if err != nil {
wfe.sendError(acme.InternalErrorProblem("unable to encode private key to PEM"), response)
return
}
response.Header().Set("Content-Type", "application/x-pem-file; charset=utf-8")
response.WriteHeader(http.StatusOK)
_, _ = response.Write(buf.Bytes())
}
}
func (wfe *WebFrontEndImpl) handleCertStatusBySerial(
_ context.Context,
response http.ResponseWriter,
request *http.Request,
) {
serialStr := strings.TrimPrefix(request.URL.Path, certStatusBySerial)
serial := big.NewInt(0)
if _, ok := serial.SetString(serialStr, 16); !ok {
response.WriteHeader(http.StatusBadRequest)
return
}
var status string
var cert *core.Certificate
var rcert *core.RevokedCertificate
if rcert = wfe.db.GetRevokedCertificateBySerial(serial); rcert != nil {
status = "Revoked"
cert = rcert.Certificate
} else if cert = wfe.db.GetCertificateBySerial(serial); cert != nil {
status = "Valid"
}
if status == "" || cert == nil {
response.WriteHeader(http.StatusNotFound)
return
}
result := struct {
Status string
Serial string
Certificate string
Reason *uint `json:",omitempty"`
RevokedAt string `json:",omitempty"`
}{
Status: status,
Serial: serial.Text(16),
Certificate: string(cert.PEM()),
}
if rcert != nil {
if rcert.Reason != nil {
result.Reason = rcert.Reason
}
result.RevokedAt = rcert.RevokedAt.UTC().String()
}
err := wfe.writeJSONResponse(response, http.StatusOK, result)
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
return
}
}
func (wfe *WebFrontEndImpl) Handler() http.Handler {
m := http.NewServeMux()
// GET & POST handlers
wfe.HandleFunc(m, DirectoryPath, wfe.Directory, http.MethodGet, http.MethodPost)
wfe.HandleFunc(m, renewalInfoPath, wfe.RenewalInfo, http.MethodGet, http.MethodPost)
// Note for noncePath: http.MethodGet also implies http.MethodHead
wfe.HandleFunc(m, noncePath, wfe.Nonce, http.MethodGet, http.MethodPost)
// POST only handlers
wfe.HandleFunc(m, newAccountPath, wfe.NewAccount, http.MethodPost)
wfe.HandleFunc(m, newOrderPath, wfe.NewOrder, http.MethodPost)
wfe.HandleFunc(m, orderFinalizePath, wfe.FinalizeOrder, http.MethodPost)
wfe.HandleFunc(m, acctPath, wfe.UpdateAccount, http.MethodPost)
wfe.HandleFunc(m, keyRolloverPath, wfe.KeyRollover, http.MethodPost)
wfe.HandleFunc(m, revokeCertPath, wfe.RevokeCert, http.MethodPost)
wfe.HandleFunc(m, certPath, wfe.Certificate, http.MethodPost)
wfe.HandleFunc(m, orderPath, wfe.Order, http.MethodPost)
wfe.HandleFunc(m, authzPath, wfe.Authz, http.MethodPost)
wfe.HandleFunc(m, challengePath, wfe.Challenge, http.MethodPost)
wfe.HandleFunc(m, ordersPath, wfe.ListOrders, http.MethodPost)
return m
}
// ManagementHandler handles the endpoints exposed on the management interface that is configured
// by the `managementListenAddress` parameter in Pebble JSON config file.
func (wfe *WebFrontEndImpl) ManagementHandler() http.Handler {
m := http.NewServeMux()
// GET only handlers
wfe.HandleManagementFunc(m, RootCertPath, wfe.handleCert(wfe.ca.GetRootCert, RootCertPath))
wfe.HandleManagementFunc(m, rootKeyPath, wfe.handleKey(wfe.ca.GetRootKey, rootKeyPath))
wfe.HandleManagementFunc(m, intermediateCertPath, wfe.handleCert(wfe.ca.GetIntermediateCert, intermediateCertPath))
wfe.HandleManagementFunc(m, intermediateKeyPath, wfe.handleKey(wfe.ca.GetIntermediateKey, intermediateKeyPath))
wfe.HandleManagementFunc(m, certStatusBySerial, wfe.handleCertStatusBySerial)
// POST only handlers
wfe.HandleFunc(m, setRenewalInfoPath, wfe.SetRenewalInfo, http.MethodPost)
return m
}
func (wfe *WebFrontEndImpl) Directory(
_ context.Context,
response http.ResponseWriter,
request *http.Request,
) {
directoryEndpoints := map[string]string{
"newNonce": noncePath,
"newAccount": newAccountPath,
"newOrder": newOrderPath,
"revokeCert": revokeCertPath,
"keyChange": keyRolloverPath,
// ARI-capable clients are expected to add the trailing slash per the
// draft. We explicitly strip the trailing slash here so that clients
// don't need to add trailing slash handling in their own code, saving
// them minimal amounts of complexity.
"renewalInfo": strings.TrimRight(renewalInfoPath, "/"),
}
// RFC 8555 §6.3 says the server's directory endpoint should support
// POST-as-GET as well as GET.
if request.Method == http.MethodPost {
postData, prob := wfe.verifyPOST(request, wfe.lookupJWK)
if prob != nil {
wfe.sendError(prob, response)
return
}
if _, prob := wfe.validPOSTAsGET(postData); prob != nil {
wfe.sendError(prob, response)
return
}
}
response.Header().Set("Content-Type", "application/json; charset=utf-8")
relDir, err := wfe.relativeDirectory(request, directoryEndpoints)
if err != nil {
wfe.sendError(acme.InternalErrorProblem("unable to create directory"), response)
return
}
_, _ = response.Write(relDir)
}
func (wfe *WebFrontEndImpl) relativeDirectory(request *http.Request, directory map[string]string) ([]byte, error) {
// Create an empty map sized equal to the provided directory to store the
// relative-ized result
relativeDir := make(map[string]interface{}, len(directory))
for k, v := range directory {
relativeDir[k] = wfe.relativeEndpoint(request, v)
}
relativeDir["meta"] = map[string]interface{}{
"termsOfService": ToSURL,
"externalAccountRequired": wfe.requireEAB,
"profiles": wfe.ca.GetProfiles(),
"caaIdentities": wfe.caaIdentities,
}
directoryJSON, err := marshalIndent(relativeDir)
// This should never happen since we are just marshaling known strings
if err != nil {
return nil, err
}
return directoryJSON, nil
}
func (wfe *WebFrontEndImpl) relativeEndpoint(request *http.Request, endpoint string) string {
proto := "http"
host := request.Host
// If the request was received via TLS, use `https://` for the protocol
if request.TLS != nil {
proto = "https"
}
// Allow upstream proxies to specify the forwarded protocol. Allow this value
// to override our own guess.
if specifiedProto := request.Header.Get("X-Forwarded-Proto"); specifiedProto != "" {
proto = specifiedProto
}
// Default to "localhost" when no request.Host is provided. Otherwise requests
// with an empty `Host` produce results like `http:///acme/new-authz`
if request.Host == "" {
host = "localhost"
}
return (&url.URL{Scheme: proto, Host: host, Path: endpoint}).String()
}
func (wfe *WebFrontEndImpl) Nonce(
_ context.Context,
response http.ResponseWriter,
request *http.Request,
) {
statusCode := http.StatusNoContent
// The ACME specification says GET requets should receive http.StatusNoContent
// and HEAD requests should receive http.StatusOK.
if request.Method == http.MethodHead {
statusCode = http.StatusOK
}
// RFC 8555 §6.3 says the server's nonce endpoint should support
// POST-as-GET as well as GET.
if request.Method == http.MethodPost {
postData, prob := wfe.verifyPOST(request, wfe.lookupJWK)
if prob != nil {
wfe.sendError(prob, response)
return
}
if _, prob := wfe.validPOSTAsGET(postData); prob != nil {
wfe.sendError(prob, response)
return
}
}
response.WriteHeader(statusCode)
}
func (wfe *WebFrontEndImpl) parseJWS(body string) (*jose.JSONWebSignature, *acme.ProblemDetails) {
// Parse the raw JWS JSON to check that:
// * the unprotected Header field is not being used.
// * the "signatures" member isn't present, just "signature".
//
// This must be done prior to `jose.parseSigned` since it will strip away
// these headers.
var unprotected struct {
Header map[string]string
Signatures []interface{}
}
if err := json.Unmarshal([]byte(body), &unprotected); err != nil {
return nil, acme.MalformedProblem(fmt.Sprint("Parse error reading JWS: ", err.Error()))
}
// ACME v2 never uses values from the unprotected JWS header. Reject JWS that
// include unprotected headers.
if unprotected.Header != nil {
return nil, acme.MalformedProblem(
"JWS \"header\" field not allowed. All headers must be in \"protected\" field")
}
// ACME v2 never uses the "signatures" array of JSON serialized JWS, just the
// mandatory "signature" field. Reject JWS that include the "signatures" array.
if len(unprotected.Signatures) > 0 {
return nil, acme.MalformedProblem(
"JWS \"signatures\" field not allowed. Only the \"signature\" field should contain a signature")
}
parsedJWS, err := jose.ParseSigned(body, goodJWSSignatureAlgorithms)
if err != nil {
var unexpectedSignAlgo *jose.ErrUnexpectedSignatureAlgorithm
if errors.As(err, &unexpectedSignAlgo) {
return nil, acme.BadSignatureAlgorithmProblem(fmt.Sprintf(
"JWS header contained unsupported algorithm, supported algorithms are: %s", goodJWSSignatureAlgorithms))
}
return nil, acme.MalformedProblem(fmt.Sprint("Parse error reading JWS: ", err.Error()))
}
if len(parsedJWS.Signatures) > 1 {
return nil, acme.MalformedProblem("Too many signatures in POST body")
}
if len(parsedJWS.Signatures) == 0 {
return nil, acme.MalformedProblem("POST JWS not signed")
}
return parsedJWS, nil
}
// jwsAuthType represents whether a given POST request is authenticated using
// a JWS with an embedded JWK (new-account, possibly revoke-cert) or an
// embedded Key ID or an unsupported/unknown auth type.
type jwsAuthType int
const (
embeddedJWK jwsAuthType = iota
embeddedKeyID
invalidAuthType
)
// checkJWSAuthType examines a JWS' protected headers to determine if
// the request being authenticated by the JWS is identified using an embedded
// JWK or an embedded key ID. If no signatures are present, or mutually
// exclusive authentication types are specified at the same time, a problem is
// returned.
func checkJWSAuthType(jws *jose.JSONWebSignature) (jwsAuthType, *acme.ProblemDetails) {
// checkJWSAuthType is called after parseJWS() which defends against the
// incorrect number of signatures.
header := jws.Signatures[0].Header
// There must not be a Key ID *and* an embedded JWK
if header.KeyID != "" && header.JSONWebKey != nil {
return invalidAuthType, acme.MalformedProblem("jwk and kid header fields are mutually exclusive")
} else if header.KeyID != "" {
return embeddedKeyID, nil
} else if header.JSONWebKey != nil {
return embeddedJWK, nil
}
return invalidAuthType, nil
}
// extractJWK returns a JSONWebKey embedded in a JWS header.
func (wfe *WebFrontEndImpl) extractJWK(_ *http.Request, jws *jose.JSONWebSignature) (*jose.JSONWebKey, *acme.ProblemDetails) {
header := jws.Signatures[0].Header
key := header.JSONWebKey
if key == nil {
return nil, acme.MalformedProblem("No JWK in JWS header")
}
if !key.Valid() {
return nil, acme.MalformedProblem("Invalid JWK in JWS header")
}
if header.KeyID != "" {
return nil, acme.MalformedProblem("jwk and kid header fields are mutually exclusive.")
}
return key, nil
}
// lookupJWK returns a JSONWebKey referenced by the "kid" (key id) field in a JWS header.
func (wfe *WebFrontEndImpl) lookupJWK(request *http.Request, jws *jose.JSONWebSignature) (*jose.JSONWebKey, *acme.ProblemDetails) {
header := jws.Signatures[0].Header
accountURL := header.KeyID
prefix := wfe.relativeEndpoint(request, acctPath)
if !strings.HasPrefix(accountURL, prefix) {
return nil, acme.MalformedProblem("Key ID (kid) in JWS header missing expected URL prefix")
}
accountID := strings.TrimPrefix(accountURL, prefix)
if accountID == "" {
return nil, acme.MalformedProblem("No key ID (kid) in JWS header")
}
account := wfe.db.GetAccountByID(accountID)
if account == nil {
return nil, acme.AccountDoesNotExistProblem(fmt.Sprintf(
"Account %s not found.", accountURL))
}
if header.JSONWebKey != nil {
return nil, acme.MalformedProblem("jwk and kid header fields are mutually exclusive.")
}
return account.Key, nil
}
func (wfe *WebFrontEndImpl) validPOST(request *http.Request) *acme.ProblemDetails {
// Section 6.2 says to reject JWS requests without the expected Content-Type
// using a status code of http.UnsupportedMediaType
if _, present := request.Header["Content-Type"]; !present {
return acme.UnsupportedMediaTypeProblem(
`missing Content-Type header on POST. ` +
`Content-Type must be "application/jose+json"`)
}
if contentType := request.Header.Get("Content-Type"); contentType != expectedJWSContentType {
return acme.UnsupportedMediaTypeProblem(
`Invalid Content-Type header on POST. ` +
`Content-Type must be "application/jose+json"`)
}
// Per 6.4.1 "Replay-Nonce" clients should not send a Replay-Nonce header in
// the HTTP request, it needs to be part of the signed JWS request body
if _, present := request.Header["Replay-Nonce"]; present {
return acme.MalformedProblem("HTTP requests should NOT contain Replay-Nonce header. Use JWS nonce field")
}
// All POSTs must have a body
if request.Body == nil {
return acme.MalformedProblem("no body on POST")
}
return nil
}
func (wfe *WebFrontEndImpl) validPOSTAsGET(postData *authenticatedPOST) (*core.Account, *acme.ProblemDetails) {
if postData == nil {
return nil, acme.InternalErrorProblem("nil authenticated POST data")
}
if !postData.postAsGet {
return nil, acme.MalformedProblem("POST-as-GET requests must have a nil body")
}
// All POST-as-GET requests are authenticated by an existing account
account, prob := wfe.getAcctByKey(postData.jwk)
if prob != nil {
return nil, prob
}
return account, nil
}
// keyExtractor is a function that returns a JSONWebKey based on input from a
// user-provided JSONWebSignature, for instance by extracting it from the input,
// or by looking it up in a database based on the input.
type keyExtractor func(*http.Request, *jose.JSONWebSignature) (*jose.JSONWebKey, *acme.ProblemDetails)
type authenticatedPOST struct {
postAsGet bool
body []byte
url string
jwk *jose.JSONWebKey
}
// NOTE: Unlike `verifyPOST` from the Boulder WFE this version does not
// presently handle the `regCheck` parameter or do any lookups for existing
// accounts.
func (wfe *WebFrontEndImpl) verifyPOST(
request *http.Request,
kx keyExtractor,
) (*authenticatedPOST, *acme.ProblemDetails) {
if prob := wfe.validPOST(request); prob != nil {
return nil, prob
}
bodyBytes, err := io.ReadAll(request.Body)
if err != nil {
return nil, acme.InternalErrorProblem("unable to read request body")
}
body := string(bodyBytes)
parsedJWS, prob := wfe.parseJWS(body)
if prob != nil {
return nil, prob
}
pubKey, prob := kx(request, parsedJWS)
if prob != nil {
return nil, prob
}
result, prob := wfe.verifyJWS(pubKey, parsedJWS, request)
if prob != nil {
return nil, prob
}
return result, nil
}
// verifyJWSSignatureAndAlgorithm verifies the pubkey and JWS algorithms are
// acceptable and that the JWS verifies with the provided pubkey.
func (wfe *WebFrontEndImpl) verifyJWSSignatureAndAlgorithm(
pubKey *jose.JSONWebKey,
parsedJWS *jose.JSONWebSignature,
) ([]byte, *acme.ProblemDetails) {
if prob := checkAlgorithm(pubKey, parsedJWS); prob != nil {
return nil, prob
}
payload, err := parsedJWS.Verify(pubKey)
if err != nil {
return nil, acme.MalformedProblem(fmt.Sprintf("JWS verification error: %s", err))
}
return payload, nil
}
// Extracts URL header parameter from parsed JWS.
// Second return value indicates whether header was found.
func (wfe *WebFrontEndImpl) extractJWSURL(
parsedJWS *jose.JSONWebSignature,
) (string, bool) {
headerURL, ok := parsedJWS.Signatures[0].Header.ExtraHeaders[jose.HeaderKey("url")].(string)
if !ok || len(headerURL) == 0 {
return "", false
}
return headerURL, true
}
func (wfe *WebFrontEndImpl) verifyJWS(
pubKey *jose.JSONWebKey,
parsedJWS *jose.JSONWebSignature,
request *http.Request,
) (*authenticatedPOST, *acme.ProblemDetails) {
payload, prob := wfe.verifyJWSSignatureAndAlgorithm(pubKey, parsedJWS)
if prob != nil {
return nil, prob
}
headerURL, ok := wfe.extractJWSURL(parsedJWS)
if !ok {
return nil, acme.MalformedProblem("JWS header parameter 'url' required.")
}
nonce := parsedJWS.Signatures[0].Header.Nonce
if len(nonce) == 0 {
return nil, acme.BadNonceProblem("JWS has no anti-replay nonce")
}
// Roll a random number between 0 and 100.
nonceRoll := rand.Intn(100)
// If the nonce is not valid OR if the nonceRoll was less than the
// nonceErrPercent, fail with an error
if !wfe.nonce.validNonce(nonce) || nonceRoll < wfe.nonceErrPercent {
return nil, acme.BadNonceProblem(fmt.Sprintf(
"JWS has an invalid anti-replay nonce: %s", nonce))
}
expectedURL := url.URL{
// NOTE(@cpu): ACME **REQUIRES** HTTPS and Pebble is hardcoded to offer the
// API over HTTPS.
Scheme: "https",
Host: request.Host,
Path: request.RequestURI,
}
if expectedURL.String() != headerURL {
return nil, acme.MalformedProblem(fmt.Sprintf(
"JWS header parameter 'url' incorrect. Expected %q, got %q",
expectedURL.String(), headerURL))
}
// In -strict mode, verify that any JWS body that is valid JSON doesn't
// include a non-empty "resource" field. This is a legacy artifiact from ACME
// v1. This won't catch an empty "resource" field but that would have been
// broken in ACMEv1 anyway and is hopefully less likely to occur in code that
// is updated for ACMEv2.
if wfe.strict {
var bodyObj struct {
Resource string
}
if err := json.Unmarshal(payload, &bodyObj); err == nil && bodyObj.Resource != "" {
return nil, acme.MalformedProblem(fmt.Sprintf(
`JWS body included JSON with a deprecated ACME v1 "resource" field (%q)`,
bodyObj.Resource))
}
}
return &authenticatedPOST{
postAsGet: string(payload) == "",
body: payload,
url: headerURL,