forked from adamlaska/boulder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwfe.go
More file actions
2427 lines (2176 loc) · 89.6 KB
/
wfe.go
File metadata and controls
2427 lines (2176 loc) · 89.6 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 wfe2
import (
"context"
"crypto/x509"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/honeycombio/beeline-go"
"github.com/honeycombio/beeline-go/wrappers/hnynethttp"
"github.com/jmhodges/clock"
"github.com/letsencrypt/boulder/core"
corepb "github.com/letsencrypt/boulder/core/proto"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/features"
"github.com/letsencrypt/boulder/goodkey"
"github.com/letsencrypt/boulder/grpc"
bgrpc "github.com/letsencrypt/boulder/grpc"
"github.com/letsencrypt/boulder/identifier"
"github.com/letsencrypt/boulder/issuance"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/metrics/measured_http"
"github.com/letsencrypt/boulder/nonce"
noncepb "github.com/letsencrypt/boulder/nonce/proto"
"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"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/ocsp"
"google.golang.org/protobuf/types/known/emptypb"
jose "gopkg.in/square/go-jose.v2"
)
// 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/"
// When we moved to authzv2, we used a "-v3" suffix to avoid confusion
// regarding ACMEv2.
authzPath = "/acme/authz-v3/"
challengePath = "/acme/chall-v3/"
certPath = "/acme/cert/"
revokeCertPath = "/acme/revoke-cert"
buildIDPath = "/build"
rolloverPath = "/acme/key-change"
newNoncePath = "/acme/new-nonce"
newOrderPath = "/acme/new-order"
orderPath = "/acme/order/"
finalizeOrderPath = "/acme/finalize/"
getAPIPrefix = "/get/"
getOrderPath = getAPIPrefix + "order/"
getAuthzPath = getAPIPrefix + "authz-v3/"
getChallengePath = getAPIPrefix + "chall-v3/"
getCertPath = getAPIPrefix + "cert/"
renewalInfoPath = getAPIPrefix + "draft-aaron-ari/renewalInfo/"
)
var errIncompleteGRPCResponse = errors.New("incomplete gRPC response message")
// 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 rapb.RegistrationAuthorityClient
SA sapb.StorageAuthorityGetterClient
log blog.Logger
clk clock.Clock
stats wfe2Stats
// certificateChains maps IssuerNameIDs to slice of []byte containing a leading
// newline and one or more PEM encoded certificates separated by a newline,
// sorted from leaf to root. The first []byte is the default certificate chain,
// and any subsequent []byte is an alternate certificate chain.
certificateChains map[issuance.IssuerNameID][][]byte
// issuerCertificates is a map of IssuerNameIDs to issuer certificates built with the
// first entry from each of the certificateChains. These certificates are used
// to verify the signature of certificates provided in revocation requests.
issuerCertificates map[issuance.IssuerNameID]*issuance.Certificate
// URL to the current subscriber agreement (should contain some version identifier)
SubscriberAgreementURL string
// DirectoryCAAIdentity is used for the /directory response's "meta"
// element's "caaIdentities" field. It should match the VA's issuerDomain
// field value.
DirectoryCAAIdentity string
// DirectoryWebsite is used for the /directory response's "meta" element's
// "website" field.
DirectoryWebsite string
// Allowed prefix for legacy accounts used by verify.go's `lookupJWK`.
// See `cmd/boulder-wfe2/main.go`'s comment on the configuration field
// `LegacyKeyIDPrefix` for more information.
LegacyKeyIDPrefix string
// Register of anti-replay nonces
nonceService *nonce.NonceService
remoteNonceService noncepb.NonceServiceClient
noncePrefixMap map[string]noncepb.NonceServiceClient
// Key policy.
keyPolicy goodkey.KeyPolicy
// CORS settings
AllowOrigins []string
// Maximum duration of a request
RequestTimeout time.Duration
// StaleTimeout determines the required staleness for resources allowed to be
// accessed via Boulder-specific GET-able APIs. Resources newer than
// staleTimeout must be accessed via POST-as-GET and the RFC 8555 ACME API. We
// do this to incentivize client developers to use the standard API.
staleTimeout time.Duration
// How long before authorizations and pending authorizations expire. The
// Boulder specific GET-able API uses these values to find the creation date
// of authorizations to determine if they are stale enough. The values should
// match the ones used by the RA.
authorizationLifetime time.Duration
pendingAuthorizationLifetime time.Duration
}
// NewWebFrontEndImpl constructs a web service for Boulder
func NewWebFrontEndImpl(
stats prometheus.Registerer,
clk clock.Clock,
keyPolicy goodkey.KeyPolicy,
certificateChains map[issuance.IssuerNameID][][]byte,
issuerCertificates map[issuance.IssuerNameID]*issuance.Certificate,
remoteNonceService noncepb.NonceServiceClient,
noncePrefixMap map[string]noncepb.NonceServiceClient,
logger blog.Logger,
staleTimeout time.Duration,
authorizationLifetime time.Duration,
pendingAuthorizationLifetime time.Duration,
) (WebFrontEndImpl, error) {
if issuerCertificates == nil || len(issuerCertificates) == 0 {
return WebFrontEndImpl{}, errors.New("must provide at least one issuer certificate")
}
if certificateChains == nil || len(certificateChains) == 0 {
return WebFrontEndImpl{}, errors.New("must provide at least one certificate chain")
}
wfe := WebFrontEndImpl{
log: logger,
clk: clk,
keyPolicy: keyPolicy,
certificateChains: certificateChains,
issuerCertificates: issuerCertificates,
stats: initStats(stats),
remoteNonceService: remoteNonceService,
noncePrefixMap: noncePrefixMap,
staleTimeout: staleTimeout,
authorizationLifetime: authorizationLifetime,
pendingAuthorizationLifetime: pendingAuthorizationLifetime,
}
if wfe.remoteNonceService == nil {
nonceService, err := nonce.NewNonceService(stats, 0, "")
if err != nil {
return WebFrontEndImpl{}, err
}
wfe.nonceService = nonceService
}
return wfe, 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) {
logEvent.Endpoint = pattern
beeline.AddFieldToTrace(ctx, "endpoint", pattern)
if request.URL != nil {
logEvent.Slug = request.URL.Path
beeline.AddFieldToTrace(ctx, "slug", request.URL.Path)
}
if request.Method != "GET" || pattern == newNoncePath {
// Historically we did not return a error to the client
// if we failed to get a new nonce. We preserve that
// behavior if using the built in nonce service, but
// if we get a failure using the new remote nonce service
// we return an internal server error so that it is
// clearer both in our metrics and to the client that
// something is wrong.
if wfe.remoteNonceService != nil {
nonceMsg, err := wfe.remoteNonceService.Nonce(ctx, &emptypb.Empty{})
if err != nil {
wfe.sendError(response, logEvent, probs.ServerInternal("unable to get nonce"), err)
return
}
response.Header().Set("Replay-Nonce", nonceMsg.Nonce)
} else {
nonce, err := wfe.nonceService.Nonce()
if err == nil {
response.Header().Set("Replay-Nonce", nonce)
} else {
logEvent.AddError("unable to make nonce: %s", err)
}
}
}
// 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 := web.RelativeEndpoint(request, directoryPath)
response.Header().Add("Link", link(directoryURL, "index"))
}
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.Warningf("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
}
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,
// prefixing it with the request protocol and 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] = web.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(stats prometheus.Registerer) http.Handler {
m := http.NewServeMux()
// Boulder specific endpoints
wfe.HandleFunc(m, buildIDPath, wfe.BuildID, "GET")
// POSTable ACME endpoints
wfe.HandleFunc(m, newAcctPath, wfe.NewAccount, "POST")
wfe.HandleFunc(m, acctPath, wfe.Account, "POST")
wfe.HandleFunc(m, revokeCertPath, wfe.RevokeCertificate, "POST")
wfe.HandleFunc(m, rolloverPath, wfe.KeyRollover, "POST")
wfe.HandleFunc(m, newOrderPath, wfe.NewOrder, "POST")
wfe.HandleFunc(m, finalizeOrderPath, wfe.FinalizeOrder, "POST")
// GETable and POST-as-GETable ACME endpoints
wfe.HandleFunc(m, directoryPath, wfe.Directory, "GET", "POST")
wfe.HandleFunc(m, newNoncePath, wfe.Nonce, "GET", "POST")
// POST-as-GETable ACME endpoints
// TODO(@cpu): After November 1st, 2020 support for "GET" to the following
// endpoints will be removed, leaving only POST-as-GET support.
wfe.HandleFunc(m, orderPath, wfe.GetOrder, "GET", "POST")
wfe.HandleFunc(m, authzPath, wfe.Authorization, "GET", "POST")
wfe.HandleFunc(m, challengePath, wfe.Challenge, "GET", "POST")
wfe.HandleFunc(m, certPath, wfe.Certificate, "GET", "POST")
// Boulder-specific GET-able resource endpoints
wfe.HandleFunc(m, getOrderPath, wfe.GetOrder, "GET")
wfe.HandleFunc(m, getAuthzPath, wfe.Authorization, "GET")
wfe.HandleFunc(m, getChallengePath, wfe.Challenge, "GET")
wfe.HandleFunc(m, getCertPath, wfe.Certificate, "GET")
// Endpoint for draft-aaron-ari
if features.Enabled(features.ServeRenewalInfo) {
wfe.HandleFunc(m, renewalInfoPath, wfe.RenewalInfo, "GET")
}
// 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 hnynethttp.WrapHandler(measured_http.New(m, wfe.clk, stats))
}
// 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) {
// All requests that are not handled by our ACME endpoints ends up
// here. Set the our logEvent endpoint to "/" and the slug to the path
// minus "/" to make sure that we properly set log information about
// the request, even in the case of a 404
logEvent.Endpoint = "/"
logEvent.Slug = request.URL.Path[1:]
// 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" {
response.Header().Set("Allow", "GET")
wfe.sendError(response, logEvent, probs.MethodNotAllowed(), errors.New("Bad method"))
return
}
addNoCacheHeader(response)
response.Header().Set("Content-Type", "text/html")
fmt.Fprintf(response, `<html>
<body>
This is an <a href="https://tools.ietf.org/html/rfc8555">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", strconv.FormatInt(requester, 10))
}
}
// 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,
}
if features.Enabled(features.ServeRenewalInfo) {
directoryEndpoints["renewalInfo"] = renewalInfoPath
}
if request.Method == http.MethodPost {
acct, prob := wfe.validPOSTAsGETForAccount(request, ctx, logEvent)
if prob != nil {
wfe.sendError(response, logEvent, prob, nil)
return
}
logEvent.Requester = acct.ID
beeline.AddFieldToTrace(ctx, "acct.id", acct.ID)
}
// 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.
metaMap := map[string]interface{}{
"termsOfService": wfe.SubscriberAgreementURL,
}
// The "meta" directory entry may also include a []string of CAA identities
if wfe.DirectoryCAAIdentity != "" {
// The specification says caaIdentities is an array of strings. In
// practice Boulder's VA only allows configuring ONE CAA identity. Given
// that constraint it doesn't make sense to allow multiple directory CAA
// identities so we use just the `wfe.DirectoryCAAIdentity` alone.
metaMap["caaIdentities"] = []string{
wfe.DirectoryCAAIdentity,
}
}
// The "meta" directory entry may also include a string with a website URL
if wfe.DirectoryWebsite != "" {
metaMap["website"] = wfe.DirectoryWebsite
}
directoryEndpoints["meta"] = metaMap
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 status code 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) {
if request.Method == http.MethodPost {
acct, prob := wfe.validPOSTAsGETForAccount(request, ctx, logEvent)
if prob != nil {
wfe.sendError(response, logEvent, prob, nil)
return
}
logEvent.Requester = acct.ID
beeline.AddFieldToTrace(ctx, "acct.id", acct.ID)
}
statusCode := http.StatusNoContent
// The ACME specification says GET requests should receive http.StatusNoContent
// and HEAD/POST-as-GET requests should receive http.StatusOK.
if request.Method != "GET" {
statusCode = http.StatusOK
}
response.WriteHeader(statusCode)
// The ACME specification says the server MUST include a Cache-Control header
// field with the "no-store" directive in responses for the newNonce resource,
// in order to prevent caching of this resource.
response.Header().Set("Cache-Control", "no-store")
}
// sendError wraps web.SendError
func (wfe *WebFrontEndImpl) sendError(response http.ResponseWriter, logEvent *web.RequestEvent, prob *probs.ProblemDetails, ierr error) {
wfe.stats.httpErrorCount.With(prometheus.Labels{"type": string(prob.Type)}).Inc()
web.SendError(wfe.log, probs.V2ErrorNS, response, logEvent, prob, ierr)
}
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(ctx, 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
}
returnExistingAcct := func(acctPB *corepb.Registration) {
if core.AcmeStatus(acctPB.Status) == core.StatusDeactivated {
// If there is an existing, but deactivated account, then return an unauthorized
// problem informing the user that this account was deactivated
wfe.sendError(response, logEvent, probs.Unauthorized(
"An account with the provided public key exists but is deactivated"), nil)
return
}
response.Header().Set("Location",
web.RelativeEndpoint(request, fmt.Sprintf("%s%d", acctPath, acctPB.Id)))
logEvent.Requester = acctPB.Id
beeline.AddFieldToTrace(ctx, "acct.id", acctPB.Id)
addRequesterHeader(response, acctPB.Id)
acct, err := grpc.PbToRegistration(acctPB)
if err != nil {
wfe.sendError(response, logEvent, probs.ServerInternal("Error marshaling account"), err)
return
}
prepAccountForDisplay(&acct)
err = wfe.writeJsonResponse(response, logEvent, http.StatusOK, 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
}
}
keyBytes, err := key.MarshalJSON()
if err != nil {
wfe.sendError(response, logEvent,
web.ProblemDetailsForError(err, "Error creating new account"), err)
return
}
existingAcct, err := wfe.SA.GetRegistrationByKey(ctx, &sapb.JSONWebKey{Jwk: keyBytes})
if err == nil {
returnExistingAcct(existingAcct)
return
} else if !errors.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, err := extractRequesterIP(request)
if err != nil {
wfe.sendError(
response,
logEvent,
probs.ServerInternal("couldn't parse the remote (that is, the client's) address"),
fmt.Errorf("Couldn't parse RemoteAddr: %s", request.RemoteAddr),
)
return
}
// Prepare account information to create corepb.Registration
ipBytes, err := ip.MarshalText()
if err != nil {
wfe.sendError(response, logEvent,
web.ProblemDetailsForError(err, "Error creating new account"), err)
return
}
var contacts []string
var contactsPresent bool
if accountCreateRequest.Contact != nil {
contactsPresent = true
contacts = *accountCreateRequest.Contact
}
// Create corepb.Registration from provided account information
reg := corepb.Registration{
Contact: contacts,
ContactsPresent: contactsPresent,
Agreement: wfe.SubscriberAgreementURL,
Key: keyBytes,
InitialIP: ipBytes,
}
// Send the registration to the RA via grpc
acctPB, err := wfe.RA.NewRegistration(ctx, ®)
if err != nil {
if errors.Is(err, berrors.Duplicate) {
existingAcct, err := wfe.SA.GetRegistrationByKey(ctx, &sapb.JSONWebKey{Jwk: keyBytes})
if err == nil {
returnExistingAcct(existingAcct)
return
}
// return error even if berrors.NotFound, as the duplicate key error we got from
// ra.NewRegistration indicates it _does_ already exist.
wfe.sendError(response, logEvent, probs.ServerInternal("failed check for existing account"), err)
return
}
wfe.sendError(response, logEvent,
web.ProblemDetailsForError(err, "Error creating new account"), err)
return
}
registrationValid := func(reg *corepb.Registration) bool {
return !(len(reg.Key) == 0 || len(reg.InitialIP) == 0) && reg.Id != 0
}
if acctPB == nil || !registrationValid(acctPB) {
wfe.sendError(response, logEvent,
web.ProblemDetailsForError(err, "Error creating new account"), err)
return
}
acct, err := bgrpc.PbToRegistration(acctPB)
if err != nil {
wfe.sendError(response, logEvent,
web.ProblemDetailsForError(err, "Error creating new account"), err)
return
}
logEvent.Requester = acct.ID
beeline.AddFieldToTrace(ctx, "acct.id", acct.ID)
addRequesterHeader(response, acct.ID)
if acct.Contact != nil {
logEvent.Contacts = *acct.Contact
beeline.AddFieldToTrace(ctx, "contacts", *acct.Contact)
}
acctURL := web.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"))
}
prepAccountForDisplay(&acct)
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) {
authzMapPB, err := wfe.SA.GetValidAuthorizations2(ctx, &sapb.GetValidAuthorizationsRequest{
RegistrationID: acctID,
Domains: names,
Now: wfe.clk.Now().UnixNano(),
})
if err != nil {
return false, err
}
authzMap, err := bgrpc.PBToAuthzMap(authzMapPB)
if err != nil {
return false, err
}
if len(names) != len(authzMap) {
return false, nil
}
missingNames := false
for _, name := range names {
if _, present := authzMap[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, revocation.Reason) *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
parsedCertificate, 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(parsedCertificate.SerialNumber)
logEvent.Extra["CertificateSerial"] = serial
beeline.AddFieldToTrace(ctx, "cert.serial", serial)
// Try to validate the signature on the provided cert using its corresponding
// issuer certificate.
issuerNameID := issuance.GetIssuerNameID(parsedCertificate)
issuerCert, ok := wfe.issuerCertificates[issuerNameID]
if !ok || issuerCert == nil {
return probs.NotFound("Certificate from unrecognized issuer")
}
err = parsedCertificate.CheckSignatureFrom(issuerCert.Certificate)
if err != nil {
return probs.NotFound("No such certificate")
}
logEvent.Extra["CertificateDNSNames"] = parsedCertificate.DNSNames
beeline.AddFieldToTrace(ctx, "cert.dnsnames", parsedCertificate.DNSNames)
if parsedCertificate.NotAfter.Before(wfe.clk.Now()) {
return probs.Unauthorized("Certificate is expired")
}
// Check the certificate status for the provided certificate to see if it is
// already revoked
certStatus, err := wfe.SA.GetCertificateStatus(ctx, &sapb.Serial{Serial: serial})
if err != nil || certStatus.Status == "" {
return probs.ServerInternal("Failed to get certificate status")
}
logEvent.Extra["CertificateStatus"] = certStatus.Status
beeline.AddFieldToTrace(ctx, "cert.status", certStatus.Status)
if core.OCSPStatus(certStatus.Status) == core.OCSPStatusRevoked {
return probs.AlreadyRevoked("Certificate already revoked")
}
// Verify the revocation reason supplied is allowed
reason := revocation.Reason(0)
if revokeRequest.Reason != nil {
if _, present := revocation.UserAllowedReasons[*revokeRequest.Reason]; !present {
reasonStr, ok := revocation.ReasonToString[revocation.Reason(*revokeRequest.Reason)]
if !ok {
reasonStr = "unknown"
}
return probs.BadRevocationReason(
"unsupported revocation reason code provided: %s (%d). Supported reasons: %s",
reasonStr,
*revokeRequest.Reason,
revocation.UserAllowedReasonsMessage)
}
reason = *revokeRequest.Reason
}
// Validate that the requester is authenticated to revoke the given certificate
prob := authorizedToRevoke(parsedCertificate, reason)
if prob != nil {
return prob
}
// 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)
_, err = wfe.RA.RevokeCertificateWithReg(ctx, &rapb.RevokeCertificateWithRegRequest{
Cert: parsedCertificate.Raw,
Code: int64(reason),
RegID: acctID,
})
if err != nil {
if errors.Is(err, berrors.Duplicate) {
// It is possible that between checking the certificate's status and
// performing the revocation, a parallel request happened and revoked the
// cert. In this case, just retrieve the certificate status again and
// return the alreadyRevoked status.
certStatus, err = wfe.SA.GetCertificateStatus(ctx, &sapb.Serial{Serial: serial})
if err != nil || certStatus.Status == "" {
return probs.ServerInternal("Failed to get certificate status")
}
if core.OCSPStatus(certStatus.Status) == core.OCSPStatusRevoked {
return probs.AlreadyRevoked("Certificate already revoked")
}
}
return web.ProblemDetailsForError(err, "Failed to revoke certificate")
}
wfe.log.Debugf("Revoked %v", serial)
return nil
}
type revocationEvidence struct {
Serial string
Reason revocation.Reason
RegID int64
Method string
}
// 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 or was the issuing account
authorizedToRevoke := func(parsedCertificate *x509.Certificate, reason revocation.Reason) *probs.ProblemDetails {
// If revocation reason is keyCompromise, reject the request.
if reason == revocation.Reason(ocsp.KeyCompromise) {
return probs.Unauthorized("Revocation with reason keyCompromise is only supported by signing with the certificate private key")
}
// Try to find a stored final certificate for the serial number
serial := core.SerialToString(parsedCertificate.SerialNumber)
cert, err := wfe.SA.GetCertificate(ctx, &sapb.Serial{Serial: serial})
if errors.Is(err, berrors.NotFound) {
// If there was an error and it was a not found error, then maybe they're
// trying to revoke via the precertificate. Try to find that instead.
cert, err = wfe.SA.GetPrecertificate(ctx, &sapb.Serial{Serial: serial})
if errors.Is(err, berrors.NotFound) {
// If looking up a precert also returned a not found error then return
// a not found problem.
return probs.NotFound("No such certificate")
} else if err != nil {
// If there was any other error looking up the precert then return
// a server internal problem.
return probs.ServerInternal("Failed to retrieve certificate")
}
} else if err != nil {
// Otherwise if the err was not nil and not a not found error, return
// a server internal problem.
return probs.ServerInternal("Failed to retrieve certificate")
}
// If the cert/precert is owned by the requester then return nil, it is an
// authorized revocation.
if cert.RegistrationID == acct.ID {
wfe.log.AuditObject("Authorizing revocation", revocationEvidence{
Serial: core.SerialToString(parsedCertificate.SerialNumber),
Reason: reason,
RegID: acct.ID,
Method: "owner",
})
return nil
}
// Otherwise check if the account, while not the owner, has equivalent authorizations
valid, err := wfe.acctHoldsAuthorizations(ctx, acct.ID, parsedCertificate.DNSNames)
if err != nil {
return probs.ServerInternal("Failed to retrieve authorizations for names in certificate")
}
// If it doesn't, return an unauthorized problem.
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")
}
wfe.log.AuditObject("Authorizing revocation", revocationEvidence{
Serial: core.SerialToString(parsedCertificate.SerialNumber),
Reason: reason,
RegID: acct.ID,
Method: "authorizations",
})
// If it does, return nil. It is an an authorized revocation.
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.