-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathwfe.go
2108 lines (1842 loc) · 64.2 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 wfe
import (
"context"
"crypto"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/mail"
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
"unicode"
"gopkg.in/square/go-jose.v2"
"github.com/letsencrypt/pebble/acme"
"github.com/letsencrypt/pebble/ca"
"github.com/letsencrypt/pebble/core"
"github.com/letsencrypt/pebble/db"
"github.com/letsencrypt/pebble/va"
)
const (
// Note: We deliberately pick endpoint paths that differ from Boulder to
// exercise clients processing of the /directory response
// We export the DirectoryPath and RootCertPath so that the pebble binary can reference it
DirectoryPath = "/dir"
RootCertPath = "/root"
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"
// 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
)
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
va *va.VAImpl
ca *ca.CAImpl
strict bool
}
const ToSURL = "data:text/plain,Do%20what%20thou%20wilt"
func New(
log *log.Logger,
db *db.MemoryStore,
va *va.VAImpl,
ca *ca.CAImpl,
strict bool) 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)
return WebFrontEndImpl{
log: log,
db: db,
nonce: newNonceMap(),
nonceErrPercent: nonceErrPercent,
va: va,
ca: ca,
strict: strict,
}
}
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["GET"] && !methodsMap["HEAD"] {
// Allow HEAD for any resource that allows GET
methods = append(methods, "HEAD")
methodsMap["HEAD"] = true
}
methodsStr := strings.Join(methods, ", ")
defaultHandler := http.StripPrefix(pattern,
&topHandler{
wfe: wfeHandlerFunc(func(ctx context.Context, response http.ResponseWriter, request *http.Request) {
// 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 == "POST" || 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)
}
func (wfe *WebFrontEndImpl) sendError(prob *acme.ProblemDetails, response http.ResponseWriter) {
problemDoc, err := marshalIndent(prob)
if err != nil {
problemDoc = []byte("{\"detail\": \"Problem marshalling error message.\"}")
}
response.Header().Set("Content-Type", "application/problem+json; charset=utf-8")
response.WriteHeader(prob.HTTPStatus)
_, _ = response.Write(problemDoc)
}
func (wfe *WebFrontEndImpl) RootCert(
ctx context.Context,
response http.ResponseWriter,
request *http.Request) {
root := wfe.ca.GetRootCert()
if root == nil {
response.WriteHeader(http.StatusServiceUnavailable)
return
}
response.Header().Set("Content-Type", "application/pem-certificate-chain; charset=utf-8")
response.WriteHeader(http.StatusOK)
_, _ = response.Write(root.PEM())
}
func (wfe *WebFrontEndImpl) Handler() http.Handler {
m := http.NewServeMux()
// GET only handlers
wfe.HandleFunc(m, DirectoryPath, wfe.Directory, "GET")
// Note for noncePath: "GET" also implies "HEAD"
wfe.HandleFunc(m, noncePath, wfe.Nonce, "GET")
wfe.HandleFunc(m, RootCertPath, wfe.RootCert, "GET")
// POST only handlers
wfe.HandleFunc(m, newAccountPath, wfe.NewAccount, "POST")
wfe.HandleFunc(m, newOrderPath, wfe.NewOrder, "POST")
wfe.HandleFunc(m, orderFinalizePath, wfe.FinalizeOrder, "POST")
wfe.HandleFunc(m, acctPath, wfe.UpdateAccount, "POST")
wfe.HandleFunc(m, keyRolloverPath, wfe.KeyRollover, "POST")
wfe.HandleFunc(m, revokeCertPath, wfe.RevokeCert, "POST")
wfe.HandleFunc(m, certPath, wfe.Certificate, "POST")
wfe.HandleFunc(m, orderPath, wfe.Order, "POST")
wfe.HandleFunc(m, authzPath, wfe.Authz, "POST")
wfe.HandleFunc(m, challengePath, wfe.Challenge, "POST")
return m
}
func (wfe *WebFrontEndImpl) Directory(
ctx context.Context,
response http.ResponseWriter,
request *http.Request) {
directoryEndpoints := map[string]string{
"newNonce": noncePath,
"newAccount": newAccountPath,
"newOrder": newOrderPath,
"revokeCert": revokeCertPath,
"keyChange": keyRolloverPath,
}
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]string{
"termsOfService": ToSURL,
}
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(
ctx 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 == "HEAD" {
statusCode = http.StatusOK
}
response.WriteHeader(statusCode)
}
func (wfe *WebFrontEndImpl) parseJWS(body string) (*jose.JSONWebSignature, error) {
// 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, errors.New("Parse error reading JWS")
}
// ACME v2 never uses values from the unprotected JWS header. Reject JWS that
// include unprotected headers.
if unprotected.Header != nil {
return nil, errors.New(
"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, errors.New(
"JWS \"signatures\" field not allowed. Only the \"signature\" field should contain a signature")
}
parsedJWS, err := jose.ParseSigned(body)
if err != nil {
return nil, errors.New("Parse error reading JWS")
}
if len(parsedJWS.Signatures) > 1 {
return nil, errors.New("Too many signatures in POST body")
}
if len(parsedJWS.Signatures) == 0 {
return nil, errors.New("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"`)
}
if _, present := request.Header["Content-Length"]; !present {
return acme.MalformedProblem("missing Content-Length header on POST")
}
// 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 := ioutil.ReadAll(request.Body)
if err != nil {
return nil, acme.InternalErrorProblem("unable to read request body")
}
body := string(bodyBytes)
parsedJWS, err := wfe.parseJWS(body)
if err != nil {
return nil, acme.MalformedProblem(err.Error())
}
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))
}
return &authenticatedPOST{
postAsGet: string(payload) == "",
body: payload,
url: headerURL,
jwk: pubKey}, nil
}
// isASCII determines if every character in a string is encoded in
// the ASCII character set.
func isASCII(str string) bool {
for _, r := range str {
if r > unicode.MaxASCII {
return false
}
}
return true
}
func (wfe *WebFrontEndImpl) verifyContacts(acct acme.Account) *acme.ProblemDetails {
contacts := acct.Contact
// Providing no Contacts is perfectly acceptable
if len(contacts) == 0 {
return nil
}
if len(contacts) > maxContactsPerAcct {
return acme.MalformedProblem(fmt.Sprintf(
"too many contacts provided: %d > %d", len(contacts), maxContactsPerAcct))
}
for _, c := range contacts {
parsed, err := url.Parse(c)
if err != nil {
return acme.InvalidContactProblem(fmt.Sprintf("contact %q is invalid", c))
}
if parsed.Scheme != "mailto" {
return acme.UnsupportedContactProblem(fmt.Sprintf(
"contact method %q is not supported", parsed.Scheme))
}
email := parsed.Opaque
// An empty or omitted Contact array should be used instead of an empty contact
if email == "" {
return acme.InvalidContactProblem("empty contact email")
}
if !isASCII(email) {
return acme.InvalidContactProblem(fmt.Sprintf(
"contact email %q contains non-ASCII characters", email))
}
// NOTE(@cpu): ParseAddress may allow invalid emails since it supports RFC 5322
// display names. This is sufficient for Pebble because we don't intend to
// use the emails for anything and check this as a best effort for client
// developers to test invalid contact problems.
_, err = mail.ParseAddress(email)
if err != nil {
return acme.InvalidContactProblem(fmt.Sprintf(
"contact email %q is invalid", email))
}
}
return nil
}
func (wfe *WebFrontEndImpl) UpdateAccount(
ctx context.Context,
response http.ResponseWriter,
request *http.Request) {
postData, prob := wfe.verifyPOST(request, wfe.lookupJWK)
if prob != nil {
wfe.sendError(prob, response)
return
}
// updateAcctReq is the ACME account information submitted by the client
var updateAcctReq struct {
Contact []string `json:"contact"`
Status string `json:"status,omitempty"`
}
var existingAcct *core.Account
if postData.postAsGet {
existingAcct, prob = wfe.validPOSTAsGET(postData)
if prob != nil {
wfe.sendError(prob, response)
return
}
} else {
err := json.Unmarshal(postData.body, &updateAcctReq)
if err != nil {
wfe.sendError(
acme.MalformedProblem("Error unmarshaling account update JSON body"), response)
return
}
existingAcct, prob = wfe.getAcctByKey(postData.jwk)
if prob != nil {
wfe.sendError(prob, response)
return
}
}
// if this update contains no contacts or deactivated status,
// simply return the existing account and return early.
if updateAcctReq.Contact == nil && updateAcctReq.Status != acme.StatusDeactivated {
if !postData.postAsGet {
wfe.sendError(acme.MalformedProblem("Use POST-as-GET to retrieve account data instead of doing an empty update"), response)
return
}
err := wfe.writeJSONResponse(response, http.StatusOK, existingAcct)
if err != nil {
wfe.sendError(acme.InternalErrorProblem("Error marshalling account"), response)
return
}
return
}
// Create a new account object with the existing data
newAcct := &core.Account{
Account: acme.Account{
Contact: existingAcct.Contact,
Status: existingAcct.Status,
Orders: existingAcct.Orders,
},
Key: existingAcct.Key,
ID: existingAcct.ID,
}
switch {
case updateAcctReq.Status == acme.StatusDeactivated:
newAcct.Status = updateAcctReq.Status
case updateAcctReq.Status != "" && updateAcctReq.Status != newAcct.Status:
wfe.sendError(
acme.MalformedProblem(fmt.Sprintf(
"Invalid account status: %q", updateAcctReq.Status)), response)
return
case updateAcctReq.Contact != nil:
newAcct.Contact = updateAcctReq.Contact
// Verify that the contact information provided is supported & valid
prob = wfe.verifyContacts(newAcct.Account)
if prob != nil {
wfe.sendError(prob, response)
return
}
}
err := wfe.db.UpdateAccountByID(existingAcct.ID, newAcct)
if err != nil {
wfe.sendError(
acme.MalformedProblem("Error storing updated account"), response)
return
}
err = wfe.writeJSONResponse(response, http.StatusOK, newAcct)
if err != nil {
wfe.sendError(acme.InternalErrorProblem("Error marshalling account"), response)
return
}
}
func (wfe *WebFrontEndImpl) verifyKeyRollover(
innerPayload []byte,
existingAcct *core.Account,
newKey *jose.JSONWebKey,
request *http.Request) *acme.ProblemDetails {
var innerContent struct {
Account string
OldKey jose.JSONWebKey
}
err := json.Unmarshal(innerPayload, &innerContent)
if err != nil {
return acme.MalformedProblem("Error unmarshaling key roll-over inner JWS body")
}
// Check account ID
prefix := wfe.relativeEndpoint(request, acctPath)
if !strings.HasPrefix(innerContent.Account, prefix) {
return acme.MalformedProblem(fmt.Sprintf("Key ID (account) in inner JWS body missing expected URL prefix (provided account value: %q)", innerContent.Account))
}
accountID := strings.TrimPrefix(innerContent.Account, prefix)
if accountID == "" {
return acme.MalformedProblem(fmt.Sprintf("No key ID (account) in inner JWS body (provided account value: %q)", innerContent.Account))
}
if accountID != existingAcct.ID {
return acme.MalformedProblem(fmt.Sprintf("Key roll-over inner JWS body contains wrong account ID (provided account value: %q)", innerContent.Account))
}
// Verify inner key
if !keyDigestEquals(innerContent.OldKey, *existingAcct.Key) {
return acme.MalformedProblem("Key roll-over inner JWS body JSON contains wrong old key")
}
// Check for same key
if keyDigestEquals(innerContent.OldKey, newKey) {
return acme.MalformedProblem("New and old key are identical")
}
return nil
}
func (wfe *WebFrontEndImpl) KeyRollover(
ctx context.Context,
response http.ResponseWriter,
request *http.Request) {
// Extract and parse outer JWS, and retrieve account
outerPostData, prob := wfe.verifyPOST(request, wfe.lookupJWK)
if prob != nil {
wfe.sendError(prob, response)
return
}
existingAcct, prob := wfe.getAcctByKey(outerPostData.jwk)
if prob != nil {
wfe.sendError(prob, response)
return
}
// Extract inner JWS
parsedInnerJWS, err := wfe.parseJWS(string(outerPostData.body))
if err != nil {
wfe.sendError(acme.MalformedProblem(err.Error()), response)
return
}
newPubKey, prob := wfe.extractJWK(request, parsedInnerJWS)
if prob != nil {
wfe.sendError(prob, response)
return
}
innerPayload, prob := wfe.verifyJWSSignatureAndAlgorithm(newPubKey, parsedInnerJWS)
if err != nil {
prob.Detail = "inner JWS error: " + prob.Detail
wfe.sendError(prob, response)
return
}
innerHeaderURL, ok := wfe.extractJWSURL(parsedInnerJWS)
if !ok {
wfe.sendError(acme.MalformedProblem("Inner JWS header parameter 'url' required."), response)
return
}
if innerHeaderURL != outerPostData.url {
wfe.sendError(acme.MalformedProblem("JWS header parameter 'url' differs for inner and outer JWS."), response)
return
}
prob = wfe.verifyKeyRollover(innerPayload, existingAcct, newPubKey, request)
if prob != nil {
wfe.sendError(prob, response)
return
}
// Ok, now change account key
err = wfe.db.ChangeAccountKey(existingAcct, newPubKey)
if err != nil {
if existingAccountError, ok := err.(*db.ExistingAccountError); ok {
acctURL := wfe.relativeEndpoint(request, fmt.Sprintf("%s%s", acctPath, existingAccountError.MatchingAccount.ID))
response.Header().Set("Location", acctURL)
response.WriteHeader(http.StatusConflict)
} else {
wfe.sendError(acme.InternalErrorProblem(fmt.Sprintf("Error rolling over account key (%s)", err.Error())), response)
}
return
}
response.WriteHeader(http.StatusOK)
}
func (wfe *WebFrontEndImpl) NewAccount(
ctx context.Context,
response http.ResponseWriter,
request *http.Request) {
// We use extractJWK rather than lookupJWK here because the account is not yet
// created, so the user provides the full key in a JWS header rather than
// referring to an existing key.
postData, prob := wfe.verifyPOST(request, wfe.extractJWK)
if prob != nil {
wfe.sendError(prob, response)
return
}
// newAcctReq is the ACME account information submitted by the client
var newAcctReq struct {
Contact []string `json:"contact"`
ToSAgreed bool `json:"termsOfServiceAgreed"`
OnlyReturnExisting bool `json:"onlyReturnExisting"`
}
err := json.Unmarshal(postData.body, &newAcctReq)
if err != nil {
wfe.sendError(
acme.MalformedProblem("Error unmarshaling body JSON"), response)
return
}
// Lookup existing account to exit early if it exists
existingAcct, _ := wfe.db.GetAccountByKey(postData.jwk)
if existingAcct != nil {
if existingAcct.Status == acme.StatusDeactivated {
// If there is an existing, but deactivated account, then return an unauthorized
// problem informing the user that this account was deactivated
wfe.sendError(acme.UnauthorizedProblem(
"An account with the provided public key exists but is deactivated"), response)
} else {
// If there is an existing account then return a Location header pointing to
// the account and a 200 OK response
acctURL := wfe.relativeEndpoint(request, fmt.Sprintf("%s%s", acctPath, existingAcct.ID))
response.Header().Set("Location", acctURL)
_ = wfe.writeJSONResponse(response, http.StatusOK, existingAcct)
}
return
} else if existingAcct == nil && newAcctReq.OnlyReturnExisting {
// If there *isn't* an existing account and the created account request
// contained OnlyReturnExisting then this is an error - return now before
// creating a new account with the key
wfe.sendError(acme.AccountDoesNotExistProblem(
"unable to find existing account for only-return-existing request"), response)
return
}
if !newAcctReq.ToSAgreed {
response.Header().Add("Link", link(ToSURL, "terms-of-service"))
wfe.sendError(
acme.AgreementRequiredProblem(
"Provided account did not agree to the terms of service"),
response)
return
}
// Create a new account object with the provided contact
newAcct := core.Account{
Account: acme.Account{
Contact: newAcctReq.Contact,
// New accounts are valid to start.
Status: acme.StatusValid,
},
Key: postData.jwk,
}
// Verify that the contact information provided is supported & valid
prob = wfe.verifyContacts(newAcct.Account)
if prob != nil {
wfe.sendError(prob, response)
return
}
count, err := wfe.db.AddAccount(&newAcct)
if err != nil {
wfe.sendError(acme.InternalErrorProblem("Error saving account"), response)
return
}
wfe.log.Printf("There are now %d accounts in memory\n", count)
acctURL := wfe.relativeEndpoint(request, fmt.Sprintf("%s%s", acctPath, newAcct.ID))
response.Header().Add("Location", acctURL)
err = wfe.writeJSONResponse(response, http.StatusCreated, newAcct)
if err != nil {
wfe.sendError(acme.InternalErrorProblem("Error marshalling account"), response)
return
}
}
// isDNSCharacter is ported from Boulder's `policy/pa.go` implementation.
func isDNSCharacter(ch byte) bool {
return ('a' <= ch && ch <= 'z') ||
('A' <= ch && ch <= 'Z') ||
('0' <= ch && ch <= '9') ||
ch == '.' || ch == '-' || ch == '*'
}
/* TODO(@cpu): Pebble's validation of domain names is still pretty weak
* compared to Boulder. We should consider adding:
* 1) Checks for the # of labels, and the size of each label
* 2) Checks against the Public Suffix List
* 3) Checks against a configured domain blocklist
* 4) Checks for malformed IDN, RLDH, etc
*/