forked from letsencrypt/boulder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wfe.go
1729 lines (1542 loc) · 62 KB
/
wfe.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 (
"bytes"
"crypto/x509"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"net"
"net/http"
"net/url"
"path"
"regexp"
"strconv"
"strings"
"time"
jose "gopkg.in/square/go-jose.v2"
"github.com/jmhodges/clock"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/net/context"
"github.com/letsencrypt/boulder/core"
corepb "github.com/letsencrypt/boulder/core/proto"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/goodkey"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/metrics"
"github.com/letsencrypt/boulder/metrics/measured_http"
"github.com/letsencrypt/boulder/nonce"
"github.com/letsencrypt/boulder/probs"
rapb "github.com/letsencrypt/boulder/ra/proto"
"github.com/letsencrypt/boulder/revocation"
sapb "github.com/letsencrypt/boulder/sa/proto"
"github.com/letsencrypt/boulder/web"
)
// Paths are the ACME-spec identified URL path-segments for various methods.
// NOTE: In metrics/measured_http we make the assumption that these are all
// lowercase plus hyphens. If you violate that assumption you should update
// measured_http.
const (
directoryPath = "/directory"
newAcctPath = "/acme/new-acct"
acctPath = "/acme/acct/"
authzPath = "/acme/authz/"
challengePath = "/acme/challenge/"
certPath = "/acme/cert/"
revokeCertPath = "/acme/revoke-cert"
issuerPath = "/acme/issuer-cert"
buildIDPath = "/build"
rolloverPath = "/acme/key-change"
newNoncePath = "/acme/new-nonce"
newOrderPath = "/acme/new-order"
orderPath = "/acme/order/"
finalizeOrderPath = "finalize-order"
)
// WebFrontEndImpl provides all the logic for Boulder's web-facing interface,
// i.e., ACME. Its members configure the paths for various ACME functions,
// plus a few other data items used in ACME. Its methods are primarily handlers
// for HTTPS requests for the various ACME functions.
type WebFrontEndImpl struct {
RA core.RegistrationAuthority
SA core.StorageGetter
log blog.Logger
clk clock.Clock
stats wfe2Stats
scope metrics.Scope
// URL configuration parameters
BaseURL string
// Issuer certificate (DER) for /acme/issuer-cert
IssuerCert []byte
// certificateChains maps AIA issuer URLs to a []byte containing a leading
// newline and one or more PEM encoded certificates separated by a newline,
// sorted from leaf to root
certificateChains map[string][]byte
// URL to the current subscriber agreement (should contain some version identifier)
SubscriberAgreementURL string
// Register of anti-replay nonces
nonceService *nonce.NonceService
// Key policy.
keyPolicy goodkey.KeyPolicy
// CORS settings
AllowOrigins []string
// Maximum duration of a request
RequestTimeout time.Duration
AcceptRevocationReason bool
AllowAuthzDeactivation bool
}
// NewWebFrontEndImpl constructs a web service for Boulder
func NewWebFrontEndImpl(
scope metrics.Scope,
clk clock.Clock,
keyPolicy goodkey.KeyPolicy,
certificateChains map[string][]byte,
logger blog.Logger,
) (WebFrontEndImpl, error) {
nonceService, err := nonce.NewNonceService(scope)
if err != nil {
return WebFrontEndImpl{}, err
}
return WebFrontEndImpl{
log: logger,
clk: clk,
nonceService: nonceService,
keyPolicy: keyPolicy,
certificateChains: certificateChains,
stats: initStats(scope),
scope: scope,
}, nil
}
// HandleFunc registers a handler at the given path. It's
// http.HandleFunc(), but with a wrapper around the handler that
// provides some generic per-request functionality:
//
// * Set a Replay-Nonce header.
//
// * Respond to OPTIONS requests, including CORS preflight requests.
//
// * Set a no cache header
//
// * Respond http.StatusMethodNotAllowed for HTTP methods other than
// those listed.
//
// * Set CORS headers when responding to CORS "actual" requests.
//
// * Never send a body in response to a HEAD request. Anything
// written by the handler will be discarded if the method is HEAD.
// Also, all handlers that accept GET automatically accept HEAD.
func (wfe *WebFrontEndImpl) HandleFunc(mux *http.ServeMux, pattern string, h web.WFEHandlerFunc, methods ...string) {
methodsMap := make(map[string]bool)
for _, m := range methods {
methodsMap[m] = true
}
if methodsMap["GET"] && !methodsMap["HEAD"] {
// Allow HEAD for any resource that allows GET
methods = append(methods, "HEAD")
methodsMap["HEAD"] = true
}
methodsStr := strings.Join(methods, ", ")
handler := http.StripPrefix(pattern, web.NewTopHandler(wfe.log,
web.WFEHandlerFunc(func(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) {
// We do not propagate errors here, because (1) they should be
// transient, and (2) they fail closed.
nonce, err := wfe.nonceService.Nonce()
if err == nil {
response.Header().Set("Replay-Nonce", nonce)
logEvent.ResponseNonce = nonce
} else {
logEvent.AddError("unable to make nonce: %s", err)
}
logEvent.Endpoint = pattern
if request.URL != nil {
logEvent.Endpoint = path.Join(logEvent.Endpoint, request.URL.Path)
}
switch request.Method {
case "HEAD":
// Go's net/http (and httptest) servers will strip out the body
// of responses for us. This keeps the Content-Length for HEAD
// requests as the same as GET requests per the spec.
case "OPTIONS":
wfe.Options(response, request, methodsStr, methodsMap)
return
}
// No cache header is set for all requests, succeed or fail.
addNoCacheHeader(response)
if !methodsMap[request.Method] {
response.Header().Set("Allow", methodsStr)
wfe.sendError(response, logEvent, probs.MethodNotAllowed(), nil)
return
}
wfe.setCORSHeaders(response, request, "")
timeout := wfe.RequestTimeout
if timeout == 0 {
timeout = 5 * time.Minute
}
ctx, cancel := context.WithTimeout(ctx, timeout)
// TODO(riking): add request context using WithValue
// Call the wrapped handler.
h(ctx, logEvent, response, request)
cancel()
}),
))
mux.Handle(pattern, handler)
}
func marshalIndent(v interface{}) ([]byte, error) {
return json.MarshalIndent(v, "", " ")
}
func (wfe *WebFrontEndImpl) writeJsonResponse(response http.ResponseWriter, logEvent *web.RequestEvent, status int, v interface{}) error {
jsonReply, err := marshalIndent(v)
if err != nil {
return err // All callers are responsible for handling this error
}
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(status)
_, err = response.Write(jsonReply)
if err != nil {
// Don't worry about returning this error because the caller will
// never handle it.
wfe.log.Warning(fmt.Sprintf("Could not write response: %s", err))
logEvent.AddError(fmt.Sprintf("failed to write response: %s", err))
}
return nil
}
// requestProto returns "http" for HTTP requests and "https" for HTTPS
// requests. It supports the use of "X-Forwarded-Proto" to override the protocol.
func requestProto(request *http.Request) string {
proto := "http"
// 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
}
return proto
}
func (wfe *WebFrontEndImpl) relativeEndpoint(request *http.Request, endpoint string) string {
var result string
host := request.Host
proto := requestProto(request)
// 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"
}
if wfe.BaseURL != "" {
result = fmt.Sprintf("%s%s", wfe.BaseURL, endpoint)
} else {
resultUrl := url.URL{Scheme: proto, Host: host, Path: endpoint}
result = resultUrl.String()
}
return result
}
const randomDirKeyExplanationLink = "https://community.letsencrypt.org/t/adding-random-entries-to-the-directory/33417"
func (wfe *WebFrontEndImpl) relativeDirectory(request *http.Request, directory map[string]interface{}) ([]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))
// Copy each entry of the provided directory into the new relative map. If
// `wfe.BaseURL` != "", use the old behaviour and prefix each endpoint with
// the `BaseURL`. Otherwise, prefix each endpoint using the request protocol
// & host.
for k, v := range directory {
if v == randomDirKeyExplanationLink {
relativeDir[k] = v
continue
}
switch v := v.(type) {
case string:
// Only relative-ize top level string values, e.g. not the "meta" element
relativeDir[k] = wfe.relativeEndpoint(request, v)
default:
// If it isn't a string, put it into the results unmodified
relativeDir[k] = v
}
}
directoryJSON, err := marshalIndent(relativeDir)
// This should never happen since we are just marshalling known strings
if err != nil {
return nil, err
}
return directoryJSON, nil
}
// Handler returns an http.Handler that uses various functions for
// various ACME-specified paths.
func (wfe *WebFrontEndImpl) Handler() http.Handler {
m := http.NewServeMux()
wfe.HandleFunc(m, directoryPath, wfe.Directory, "GET")
wfe.HandleFunc(m, newAcctPath, wfe.NewAccount, "POST")
wfe.HandleFunc(m, acctPath, wfe.Account, "POST")
wfe.HandleFunc(m, authzPath, wfe.Authorization, "GET", "POST")
wfe.HandleFunc(m, challengePath, wfe.Challenge, "GET", "POST")
wfe.HandleFunc(m, certPath, wfe.Certificate, "GET")
wfe.HandleFunc(m, revokeCertPath, wfe.RevokeCertificate, "POST")
wfe.HandleFunc(m, issuerPath, wfe.Issuer, "GET")
wfe.HandleFunc(m, buildIDPath, wfe.BuildID, "GET")
wfe.HandleFunc(m, rolloverPath, wfe.KeyRollover, "POST")
wfe.HandleFunc(m, newNoncePath, wfe.Nonce, "GET")
wfe.HandleFunc(m, newOrderPath, wfe.NewOrder, "POST")
wfe.HandleFunc(m, orderPath, wfe.Order, "GET", "POST")
// We don't use our special HandleFunc for "/" because it matches everything,
// meaning we can wind up returning 405 when we mean to return 404. See
// https://github.com/letsencrypt/boulder/issues/717
m.Handle("/", web.NewTopHandler(wfe.log, web.WFEHandlerFunc(wfe.Index)))
return measured_http.New(m, wfe.clk, wfe.scope)
}
// Method implementations
// Index serves a simple identification page. It is not part of the ACME spec.
func (wfe *WebFrontEndImpl) Index(ctx context.Context, logEvent *web.RequestEvent, response http.ResponseWriter, request *http.Request) {
// http://golang.org/pkg/net/http/#example_ServeMux_Handle
// The "/" pattern matches everything, so we need to check
// that we're at the root here.
if request.URL.Path != "/" {
logEvent.AddError("Resource not found")
http.NotFound(response, request)
response.Header().Set("Content-Type", "application/problem+json")
return
}
if request.Method != "GET" {
logEvent.AddError("Bad method")
response.Header().Set("Allow", "GET")
wfe.sendError(response, logEvent, probs.MethodNotAllowed(), nil)
return
}
addNoCacheHeader(response)
response.Header().Set("Content-Type", "text/html")
response.Write([]byte(fmt.Sprintf(`<html>
<body>
This is an <a href="https://github.com/ietf-wg-acme/acme/">ACME</a>
Certificate Authority running <a href="https://github.com/letsencrypt/boulder">Boulder</a>.
JSON directory is available at <a href="%s">%s</a>.
</body>
</html>
`, directoryPath, directoryPath)))
}
func addNoCacheHeader(w http.ResponseWriter) {
w.Header().Add("Cache-Control", "public, max-age=0, no-cache")
}
func addRequesterHeader(w http.ResponseWriter, requester int64) {
if requester > 0 {
w.Header().Set("Boulder-Requester", fmt.Sprintf("%d", requester))
}
}
// Directory is an HTTP request handler that provides the directory
// object stored in the WFE's DirectoryEndpoints member with paths prefixed
// using the `request.Host` of the HTTP request.
func (wfe *WebFrontEndImpl) Directory(
ctx context.Context,
logEvent *web.RequestEvent,
response http.ResponseWriter,
request *http.Request) {
directoryEndpoints := map[string]interface{}{
"newAccount": newAcctPath,
"newNonce": newNoncePath,
"revokeCert": revokeCertPath,
"newOrder": newOrderPath,
"keyChange": rolloverPath,
}
// Add a random key to the directory in order to make sure that clients don't hardcode an
// expected set of keys. This ensures that we can properly extend the directory when we
// need to add a new endpoint or meta element.
directoryEndpoints[core.RandomString(8)] = randomDirKeyExplanationLink
// ACME since draft-02 describes an optional "meta" directory entry. The
// meta entry may optionally contain a "termsOfService" URI for the
// current ToS.
directoryEndpoints["meta"] = map[string]string{
"termsOfService": wfe.SubscriberAgreementURL,
}
response.Header().Set("Content-Type", "application/json")
relDir, err := wfe.relativeDirectory(request, directoryEndpoints)
if err != nil {
marshalProb := probs.ServerInternal("unable to marshal JSON directory")
wfe.sendError(response, logEvent, marshalProb, nil)
return
}
response.Write(relDir)
}
// Nonce is an endpoint for getting a fresh nonce with an HTTP GET or HEAD
// request. This endpoint only returns a no content header - the `HandleFunc`
// wrapper ensures that a nonce is written in the correct response header.
func (wfe *WebFrontEndImpl) Nonce(
ctx context.Context,
logEvent *web.RequestEvent,
response http.ResponseWriter,
request *http.Request) {
response.WriteHeader(http.StatusNoContent)
}
// sendError sends an error response represented by the given ProblemDetails,
// and, if the ProblemDetails.Type is ServerInternalProblem, audit logs the
// internal ierr. The rendered Problem will have its Type prefixed with the ACME
// v2 error namespace.
func (wfe *WebFrontEndImpl) sendError(response http.ResponseWriter, logEvent *web.RequestEvent, prob *probs.ProblemDetails, ierr error) {
// Determine the HTTP status code to use for this problem
code := probs.ProblemDetailsToStatusCode(prob)
// Record details to the log event
logEvent.AddError(fmt.Sprintf("%d :: %s :: %s", prob.HTTPStatus, prob.Type, prob.Detail))
// Only audit log internal errors so users cannot purposefully cause
// auditable events.
if prob.Type == probs.ServerInternalProblem {
if ierr != nil {
wfe.log.AuditErr(fmt.Sprintf("Internal error - %s - %s", prob.Detail, ierr))
} else {
wfe.log.AuditErr(fmt.Sprintf("Internal error - %s", prob.Detail))
}
}
// Increment a stat for this problem type
wfe.stats.httpErrorCount.With(prometheus.Labels{"type": string(prob.Type)}).Inc()
// Prefix the problem type with the ACME V2 error namespace and marshal to JSON
prob.Type = probs.V2ErrorNS + prob.Type
problemDoc, err := marshalIndent(prob)
if err != nil {
wfe.log.AuditErr(fmt.Sprintf("Could not marshal error message: %s - %+v", err, prob))
problemDoc = []byte("{\"detail\": \"Problem marshalling error message.\"}")
}
// Write the JSON problem response
response.Header().Set("Content-Type", "application/problem+json")
response.WriteHeader(code)
response.Write(problemDoc)
}
func link(url, relation string) string {
return fmt.Sprintf("<%s>;rel=\"%s\"", url, relation)
}
// NewAccount is used by clients to submit a new account
func (wfe *WebFrontEndImpl) NewAccount(
ctx context.Context,
logEvent *web.RequestEvent,
response http.ResponseWriter,
request *http.Request) {
// NewAccount uses `validSelfAuthenticatedPOST` instead of
// `validPOSTforAccount` because there is no account to authenticate against
// until after it is created!
body, key, prob := wfe.validSelfAuthenticatedPOST(request, logEvent)
if prob != nil {
// validSelfAuthenticatedPOST handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
return
}
var accountCreateRequest struct {
Contact *[]string `json:"contact"`
TermsOfServiceAgreed bool `json:"termsOfServiceAgreed"`
OnlyReturnExisting bool `json:"onlyReturnExisting"`
}
err := json.Unmarshal(body, &accountCreateRequest)
if err != nil {
wfe.sendError(response, logEvent, probs.Malformed("Error unmarshaling JSON"), err)
return
}
existingAcct, err := wfe.SA.GetRegistrationByKey(ctx, key)
if err == nil {
response.Header().Set("Location",
wfe.relativeEndpoint(request, fmt.Sprintf("%s%d", acctPath, existingAcct.ID)))
response.WriteHeader(http.StatusOK)
return
} else if !berrors.Is(err, berrors.NotFound) {
wfe.sendError(response, logEvent, probs.ServerInternal("failed check for existing account"), err)
return
}
// If the request included a true "OnlyReturnExisting" field and we did not
// find an existing registration with the key specified then we must return an
// error and not create a new account.
if accountCreateRequest.OnlyReturnExisting {
wfe.sendError(response, logEvent, probs.AccountDoesNotExist(
"No account exists with the provided key"), nil)
return
}
if !accountCreateRequest.TermsOfServiceAgreed {
wfe.sendError(response, logEvent, probs.Malformed("must agree to terms of service"), nil)
return
}
ip := net.ParseIP(request.Header.Get("X-Real-IP"))
if ip == nil {
host, _, err := net.SplitHostPort(request.RemoteAddr)
if err == nil {
ip = net.ParseIP(host)
} else {
logEvent.AddError("Couldn't parse RemoteAddr: %s", request.RemoteAddr)
wfe.sendError(response, logEvent, probs.ServerInternal("couldn't parse the remote (that is, the client's) address"), nil)
return
}
}
acct, err := wfe.RA.NewRegistration(ctx, core.Registration{
Contact: accountCreateRequest.Contact,
Agreement: wfe.SubscriberAgreementURL,
Key: key,
InitialIP: ip,
})
if err != nil {
wfe.sendError(response, logEvent,
web.ProblemDetailsForError(err, "Error creating new account"), err)
return
}
logEvent.Requester = acct.ID
addRequesterHeader(response, acct.ID)
logEvent.Contacts = acct.Contact
acctURL := wfe.relativeEndpoint(request, fmt.Sprintf("%s%d", acctPath, acct.ID))
response.Header().Add("Location", acctURL)
if len(wfe.SubscriberAgreementURL) > 0 {
response.Header().Add("Link", link(wfe.SubscriberAgreementURL, "terms-of-service"))
}
err = wfe.writeJsonResponse(response, logEvent, http.StatusCreated, acct)
if err != nil {
// ServerInternal because we just created this account, and it
// should be OK.
wfe.sendError(response, logEvent, probs.ServerInternal("Error marshaling account"), err)
return
}
}
func (wfe *WebFrontEndImpl) acctHoldsAuthorizations(ctx context.Context, acctID int64, names []string) (bool, error) {
authz, err := wfe.SA.GetValidAuthorizations(ctx, acctID, names, wfe.clk.Now())
if err != nil {
return false, err
}
if len(names) != len(authz) {
return false, nil
}
missingNames := false
for _, name := range names {
if _, present := authz[name]; !present {
missingNames = true
}
}
return !missingNames, nil
}
// authorizedToRevokeCert is a callback function that can be used to validate if
// a given requester is authorized to revoke the certificate parsed out of the
// revocation request from the inner JWS. If the requester is not authorized to
// revoke the certificate a problem is returned. It is expected to be a closure
// containing additional state (an account ID or key) that will be used to make
// the decision.
type authorizedToRevokeCert func(*x509.Certificate) *probs.ProblemDetails
// processRevocation accepts the payload for a revocation request along with
// an account ID and a callback used to decide if the requester is authorized to
// revoke a given certificate. If the request can not be authenticated or the
// requester is not authorized to revoke the certificate requested a problem is
// returned. Otherwise the certificate is marked revoked through the SA.
func (wfe *WebFrontEndImpl) processRevocation(
ctx context.Context,
jwsBody []byte,
acctID int64,
authorizedToRevoke authorizedToRevokeCert,
request *http.Request,
logEvent *web.RequestEvent) *probs.ProblemDetails {
// Read the revoke request from the JWS payload
var revokeRequest struct {
CertificateDER core.JSONBuffer `json:"certificate"`
Reason *revocation.Reason `json:"reason"`
}
if err := json.Unmarshal(jwsBody, &revokeRequest); err != nil {
return probs.Malformed("Unable to JSON parse revoke request")
}
// Parse the provided certificate
providedCert, err := x509.ParseCertificate(revokeRequest.CertificateDER)
if err != nil {
return probs.Malformed("Unable to parse certificate DER")
}
// Compute and record the serial number of the provided certificate
serial := core.SerialToString(providedCert.SerialNumber)
logEvent.Extra["ProvidedCertificateSerial"] = serial
// Lookup the certificate by the serial. If the certificate wasn't found, or
// it wasn't a byte-for-byte match to the certificate requested for
// revocation, return an error
cert, err := wfe.SA.GetCertificate(ctx, serial)
if err != nil || !bytes.Equal(cert.DER, revokeRequest.CertificateDER) {
return probs.NotFound("No such certificate")
}
// Parse the certificate into memory
parsedCertificate, err := x509.ParseCertificate(cert.DER)
if err != nil {
// InternalServerError because cert.DER came from our own DB.
return probs.ServerInternal("invalid parse of stored certificate")
}
logEvent.Extra["RetrievedCertificateSerial"] = core.SerialToString(parsedCertificate.SerialNumber)
logEvent.Extra["RetrievedCertificateDNSNames"] = parsedCertificate.DNSNames
// Check the certificate status for the provided certificate to see if it is
// already revoked
certStatus, err := wfe.SA.GetCertificateStatus(ctx, serial)
if err != nil {
return probs.NotFound("Certificate status not yet available")
}
logEvent.Extra["CertificateStatus"] = certStatus.Status
if certStatus.Status == core.OCSPStatusRevoked {
return probs.Conflict("Certificate already revoked")
}
// Validate that the requester is authenticated to revoke the given certificate
prob := authorizedToRevoke(parsedCertificate)
if prob != nil {
return prob
}
// Verify the revocation reason supplied is allowed
reason := revocation.Reason(0)
if revokeRequest.Reason != nil && wfe.AcceptRevocationReason {
if _, present := revocation.UserAllowedReasons[*revokeRequest.Reason]; !present {
return probs.Malformed("unsupported revocation reason code provided")
}
reason = *revokeRequest.Reason
}
// Revoke the certificate. AcctID may be 0 if there is no associated account
// (e.g. it was a self-authenticated JWS using the certificate public key)
if err := wfe.RA.RevokeCertificateWithReg(ctx, *parsedCertificate, reason, acctID); err != nil {
return web.ProblemDetailsForError(err, "Failed to revoke certificate")
}
wfe.log.Debug(fmt.Sprintf("Revoked %v", serial))
return nil
}
// revokeCertByKeyID processes an outer JWS as a revocation request that is
// authenticated by a KeyID and the associated account.
func (wfe *WebFrontEndImpl) revokeCertByKeyID(
ctx context.Context,
outerJWS *jose.JSONWebSignature,
request *http.Request,
logEvent *web.RequestEvent) *probs.ProblemDetails {
// For Key ID revocations we authenticate the outer JWS by using
// `validJWSForAccount` similar to other WFE endpoints
jwsBody, _, acct, prob := wfe.validJWSForAccount(outerJWS, request, ctx, logEvent)
if prob != nil {
return prob
}
// For Key ID revocations we decide if an account is able to revoke a specific
// certificate by checking that the account has valid authorizations for all
// of the names in the certificate
authorizedToRevoke := func(parsedCertificate *x509.Certificate) *probs.ProblemDetails {
valid, err := wfe.acctHoldsAuthorizations(ctx, acct.ID, parsedCertificate.DNSNames)
if err != nil {
return probs.ServerInternal("Failed to retrieve authorizations for names in certificate")
}
if !valid {
return probs.Unauthorized(
"The key ID specified in the revocation request does not hold valid authorizations for all names in the certificate to be revoked")
}
return nil
}
return wfe.processRevocation(ctx, jwsBody, acct.ID, authorizedToRevoke, request, logEvent)
}
// revokeCertByJWK processes an outer JWS as a revocation request that is
// authenticated by an embedded JWK. E.g. in the case where someone is
// requesting a revocation by using the keypair associated with the certificate
// to be revoked
func (wfe *WebFrontEndImpl) revokeCertByJWK(
ctx context.Context,
outerJWS *jose.JSONWebSignature,
request *http.Request,
logEvent *web.RequestEvent) *probs.ProblemDetails {
// We maintain the requestKey as a var that is closed-over by the
// `authorizedToRevoke` function to use
var requestKey *jose.JSONWebKey
// For embedded JWK revocations we authenticate the outer JWS by using
// `validSelfAuthenticatedJWS` similar to new-reg and key rollover.
// We do *not* use `validSelfAuthenticatedPOST` here because we've already
// read the HTTP request body in `parseJWSRequest` and it is now empty.
jwsBody, jwk, prob := wfe.validSelfAuthenticatedJWS(outerJWS, request, logEvent)
if prob != nil {
return prob
}
requestKey = jwk
// For embedded JWK revocations we decide if a requester is able to revoke a specific
// certificate by checking that to-be-revoked certificate has the same public
// key as the JWK that was used to authenticate the request
authorizedToRevoke := func(parsedCertificate *x509.Certificate) *probs.ProblemDetails {
if !core.KeyDigestEquals(requestKey, parsedCertificate.PublicKey) {
return probs.Unauthorized(
"JWK embedded in revocation request must be the same public key as the cert to be revoked")
}
return nil
}
// We use `0` as the account ID provided to `processRevocation` because this
// is a self-authenticated request.
return wfe.processRevocation(ctx, jwsBody, 0, authorizedToRevoke, request, logEvent)
}
// RevokeCertificate is used by clients to request the revocation of a cert. The
// revocation request is handled uniquely based on the method of authentication
// used.
func (wfe *WebFrontEndImpl) RevokeCertificate(
ctx context.Context,
logEvent *web.RequestEvent,
response http.ResponseWriter,
request *http.Request) {
// The ACME specification handles the verification of revocation requests
// differently from other endpoints. For this reason we do *not* immediately
// call `wfe.validPOSTForAccount` like all of the other endpoints.
// For this endpoint we need to accept a JWS with an embedded JWK, or a JWS
// with an embedded key ID, handling each case differently in terms of which
// certificates are authorized to be revoked by the requester
// Parse the JWS from the HTTP Request
jws, prob := wfe.parseJWSRequest(request)
if prob != nil {
wfe.sendError(response, logEvent, prob, nil)
return
}
// Figure out which type of authentication this JWS uses
authType, prob := checkJWSAuthType(jws)
if prob != nil {
wfe.sendError(response, logEvent, prob, nil)
return
}
// Handle the revocation request according to how it is authenticated, or if
// the authentication type is unknown, error immediately
if authType == embeddedKeyID {
prob = wfe.revokeCertByKeyID(ctx, jws, request, logEvent)
addRequesterHeader(response, logEvent.Requester)
} else if authType == embeddedJWK {
prob = wfe.revokeCertByJWK(ctx, jws, request, logEvent)
} else {
prob = probs.Malformed("Malformed JWS, no KeyID or embedded JWK")
}
if prob != nil {
wfe.sendError(response, logEvent, prob, nil)
return
}
response.WriteHeader(http.StatusOK)
}
func (wfe *WebFrontEndImpl) logCsr(request *http.Request, cr core.CertificateRequest, account core.Registration) {
var csrLog = struct {
ClientAddr string
CSR string
Registration core.Registration
}{
ClientAddr: web.GetClientAddr(request),
CSR: hex.EncodeToString(cr.Bytes),
Registration: account,
}
wfe.log.AuditObject("Certificate request", csrLog)
}
// Challenge handles POST requests to challenge URLs. Such requests are clients'
// responses to the server's challenges.
func (wfe *WebFrontEndImpl) Challenge(
ctx context.Context,
logEvent *web.RequestEvent,
response http.ResponseWriter,
request *http.Request) {
notFound := func() {
wfe.sendError(response, logEvent, probs.NotFound("No such challenge"), nil)
}
// Challenge URLs are of the form /acme/challenge/<auth id>/<challenge id>.
// Here we parse out the id components.
slug := strings.Split(request.URL.Path, "/")
if len(slug) != 2 {
notFound()
return
}
authorizationID := slug[0]
challengeID, err := strconv.ParseInt(slug[1], 10, 64)
if err != nil {
notFound()
return
}
logEvent.Extra["AuthorizationID"] = authorizationID
logEvent.Extra["ChallengeID"] = challengeID
authz, err := wfe.SA.GetAuthorization(ctx, authorizationID)
if err != nil {
if berrors.Is(err, berrors.NotFound) {
notFound()
} else {
wfe.sendError(response, logEvent, probs.ServerInternal("Problem getting authorization"), err)
}
return
}
// After expiring, challenges are inaccessible
if authz.Expires == nil || authz.Expires.Before(wfe.clk.Now()) {
wfe.sendError(response, logEvent, probs.NotFound("Expired authorization"), nil)
return
}
// Check that the requested challenge exists within the authorization
challengeIndex := authz.FindChallenge(challengeID)
if challengeIndex == -1 {
notFound()
return
}
challenge := authz.Challenges[challengeIndex]
logEvent.Extra["ChallengeType"] = challenge.Type
logEvent.Extra["AuthorizationRegistrationID"] = authz.RegistrationID
logEvent.Extra["AuthorizationIdentifier"] = authz.Identifier
logEvent.Extra["AuthorizationStatus"] = authz.Status
logEvent.Extra["AuthorizationExpires"] = authz.Expires
switch request.Method {
case "GET", "HEAD":
wfe.getChallenge(ctx, response, request, authz, &challenge, logEvent)
case "POST":
wfe.postChallenge(ctx, response, request, authz, challengeIndex, logEvent)
}
}
// prepChallengeForDisplay takes a core.Challenge and prepares it for display to
// the client by filling in its URL field and clearing its ID and URI fields.
func (wfe *WebFrontEndImpl) prepChallengeForDisplay(request *http.Request, authz core.Authorization, challenge *core.Challenge) {
// Update the challenge URL to be relative to the HTTP request Host
challenge.URL = wfe.relativeEndpoint(request, fmt.Sprintf("%s%s/%d", challengePath, authz.ID, challenge.ID))
// Ensure the challenge URI and challenge ID aren't written by setting them to
// values that the JSON omitempty tag considers empty
challenge.URI = ""
challenge.ID = 0
// Historically the Type field of a problem was always prefixed with a static
// error namespace. To support the V2 API and migrating to the correct IETF
// namespace we now prefix the Type with the correct namespace at runtime when
// we write the problem JSON to the user. We skip this process if the
// challenge error type has already been prefixed with the V1ErrorNS.
if challenge.Error != nil && !strings.HasPrefix(string(challenge.Error.Type), probs.V1ErrorNS) {
challenge.Error.Type = probs.V2ErrorNS + challenge.Error.Type
}
}
// prepAuthorizationForDisplay takes a core.Authorization and prepares it for
// display to the client by clearing its ID and RegistrationID fields, and
// preparing all its challenges.
func (wfe *WebFrontEndImpl) prepAuthorizationForDisplay(request *http.Request, authz *core.Authorization) {
for i := range authz.Challenges {
wfe.prepChallengeForDisplay(request, *authz, &authz.Challenges[i])
}
authz.ID = ""
authz.RegistrationID = 0
// Combinations are a relic of the V1 API. Since they are tagged omitempty we
// can set this field to nil to avoid sending it to users of the V2 API.
authz.Combinations = nil
// The ACME spec forbids allowing "*" in authorization identifiers. Boulder
// allows this internally as a means of tracking when an authorization
// corresponds to a wildcard request (e.g. to handle CAA properly). We strip
// the "*." prefix from the Authz's Identifier's Value here to respect the law
// of the protocol.
if strings.HasPrefix(authz.Identifier.Value, "*.") {
authz.Identifier.Value = strings.TrimPrefix(authz.Identifier.Value, "*.")
// Mark that the authorization corresponds to a wildcard request since we've
// now removed the wildcard prefix from the identifier.
authz.Wildcard = true
}
}
func (wfe *WebFrontEndImpl) getChallenge(
ctx context.Context,
response http.ResponseWriter,
request *http.Request,
authz core.Authorization,
challenge *core.Challenge,
logEvent *web.RequestEvent) {
wfe.prepChallengeForDisplay(request, authz, challenge)
authzURL := wfe.relativeEndpoint(request, authzPath+string(authz.ID))
response.Header().Add("Location", challenge.URL)
response.Header().Add("Link", link(authzURL, "up"))
err := wfe.writeJsonResponse(response, logEvent, http.StatusOK, challenge)
if err != nil {
// InternalServerError because this is a failure to decode data passed in
// by the caller, which got it from the DB.
wfe.sendError(response, logEvent, probs.ServerInternal("Failed to marshal challenge"), err)
return
}
}
func (wfe *WebFrontEndImpl) postChallenge(
ctx context.Context,
response http.ResponseWriter,
request *http.Request,
authz core.Authorization,
challengeIndex int,
logEvent *web.RequestEvent) {
body, _, currAcct, prob := wfe.validPOSTForAccount(request, ctx, logEvent)
addRequesterHeader(response, logEvent.Requester)
if prob != nil {
// validPOSTForAccount handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
return
}
// Any version of the agreement is acceptable here. Version match is enforced in
// wfe.Account when agreeing the first time. Agreement updates happen
// by mailing subscribers and don't require an account update.
if currAcct.Agreement == "" {
wfe.sendError(response, logEvent,
probs.Unauthorized("Account must agree to subscriber agreement before any further actions"), nil)
return
}
// Check that the account ID matching the key used matches
// the account ID on the authz object
if currAcct.ID != authz.RegistrationID {
wfe.sendError(response,
logEvent,
probs.Unauthorized("User account ID doesn't match account ID in authorization"),
nil,
)
return
}
var challengeUpdate core.Challenge
if err := json.Unmarshal(body, &challengeUpdate); err != nil {
wfe.sendError(response, logEvent, probs.Malformed("Error unmarshaling challenge response"), err)
return
}
// Ask the RA to update this authorization
updatedAuthorization, err := wfe.RA.UpdateAuthorization(ctx, authz, challengeIndex, challengeUpdate)
if err != nil {
wfe.sendError(response, logEvent, web.ProblemDetailsForError(err, "Unable to update challenge"), err)
return
}
// assumption: UpdateAuthorization does not modify order of challenges
challenge := updatedAuthorization.Challenges[challengeIndex]
wfe.prepChallengeForDisplay(request, authz, &challenge)
authzURL := wfe.relativeEndpoint(request, authzPath+string(authz.ID))
response.Header().Add("Location", challenge.URL)
response.Header().Add("Link", link(authzURL, "up"))
err = wfe.writeJsonResponse(response, logEvent, http.StatusOK, challenge)
if err != nil {
// ServerInternal because we made the challenges, they should be OK
wfe.sendError(response, logEvent, probs.ServerInternal("Failed to marshal challenge"), err)
return
}
}
// Account is used by a client to submit an update to their account.
func (wfe *WebFrontEndImpl) Account(