-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandler.go
More file actions
1335 lines (1250 loc) · 42.5 KB
/
Copy pathhandler.go
File metadata and controls
1335 lines (1250 loc) · 42.5 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 acme
import (
"bytes"
"context"
"crypto/rand"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"log/slog"
"math"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/letsencrypt/cactus/ca"
"github.com/letsencrypt/cactus/cert"
"github.com/letsencrypt/cactus/landmark"
cactusmetrics "github.com/letsencrypt/cactus/metrics"
"github.com/letsencrypt/cactus/tlogx"
)
// ChallengeMode controls how challenges are validated.
type ChallengeMode string
const (
ChallengeAutoPass ChallengeMode = "auto-pass"
ChallengeHTTP01 ChallengeMode = "http-01"
)
// Config configures the Server.
type Config struct {
// ExternalURL is the base URL the server is reachable at, used to
// construct directory entries and resource URLs.
ExternalURL string
// Issuer drives X.509 issuance once an order is finalized.
Issuer *ca.Issuer
// ChallengeMode is auto-pass for tests; http-01 not yet implemented.
ChallengeMode ChallengeMode
// OrderLifetime bounds how long an order remains valid.
OrderLifetime time.Duration
// Logger receives slog records; defaults to slog.Default().
Logger *slog.Logger
// OrdersByStatus is the labelled counter for terminal-status
// transitions: incremented to "valid" on successful issuance and
// "invalid" on failure. Optional.
OrdersByStatus cactusmetrics.CounterVec
// Landmarks, if non-nil, enables the rel="acme-optional-alternate" URL
// /cert/{id}/landmark-relative/{number}: it returns the
// landmark-relative cert once the covering landmark exists, and HTTP
// 202 (Accepted) until then.
Landmarks *landmark.Sequence
// SubtreeProof, if set, is used to compute inclusion proofs for
// landmark-relative cert assembly. Must be set whenever Landmarks
// is. Typically `(*log.Log).SubtreeProof`.
SubtreeProof func(start, end, index uint64) (tlogx.Hash, []tlogx.Hash, error)
// LogID is the issuance log's trust anchor ID (§5.2). Used for
// landmark-relative cert assembly and as the fallback for the
// standalone-cert `trust_anchor_id` property emitted in
// application/pem-certificate-chain-with-properties when CAID is unset.
LogID cert.TrustAnchorID
// CAID is the CA's CA ID (§5.1). Emitted as the standalone cert's
// `trust_anchor_id` property (draft-05 §8.1); landmark trust anchor
// IDs are derived from it and LogNumber (CA-ID.1.logNumber.L, §6.4.1).
CAID cert.TrustAnchorID
// LogNumber is the issuance log's number (§5.2). Required whenever
// Landmarks is set.
LogNumber uint16
}
// Server is the ACME HTTP server.
type Server struct {
cfg Config
state *State
logger *slog.Logger
// certs holds DER-encoded certs by their certificate ID. Mirrored
// to disk via certStore when storage is attached.
certs map[string][]byte
certStore *CertStore
}
// New constructs a Server. The Server.SetExternalURL setter exists so
// tests using httptest.NewServer can plug in the URL after the listener
// is up.
func New(cfg Config) (*Server, error) {
if cfg.Issuer == nil {
return nil, fmt.Errorf("acme: Issuer required")
}
if cfg.OrderLifetime == 0 {
cfg.OrderLifetime = 24 * time.Hour
}
if cfg.ChallengeMode == "" {
cfg.ChallengeMode = ChallengeAutoPass
}
if cfg.Logger == nil {
cfg.Logger = slog.Default()
}
return &Server{
cfg: cfg,
state: NewState(),
logger: cfg.Logger,
certs: make(map[string][]byte),
}, nil
}
// Handler returns the routed HTTP handler.
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /directory", s.handleDirectory)
mux.HandleFunc("HEAD /new-nonce", s.handleNewNonce)
mux.HandleFunc("GET /new-nonce", s.handleNewNonce)
mux.HandleFunc("POST /new-account", s.handleNewAccount)
mux.HandleFunc("POST /account/{id}", s.handleAccount)
mux.HandleFunc("POST /account/{id}/orders", s.handleAccountOrders)
mux.HandleFunc("POST /new-order", s.handleNewOrder)
mux.HandleFunc("POST /authz/{id}", s.handleAuthz)
mux.HandleFunc("POST /chall/{id}", s.handleChallenge)
mux.HandleFunc("POST /order/{id}", s.handleOrder)
mux.HandleFunc("POST /finalize/{id}", s.handleFinalize)
mux.HandleFunc("POST /cert/{id}", s.handleCert)
mux.HandleFunc("POST /cert/{id}/landmark-relative/{number}", s.handleCertLandmarkRelative)
return mux
}
// urlFor returns a fully-qualified URL relative to the configured external URL.
func (s *Server) urlFor(path string) string {
base := strings.TrimRight(s.cfg.ExternalURL, "/")
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
return base + path
}
// SetExternalURL updates the base URL used in directory entries, account
// locations, etc. Tests using httptest.NewServer call this after the
// listener address is known.
func (s *Server) SetExternalURL(u string) {
s.cfg.ExternalURL = u
}
// AttachStorage wires a storage backend so accounts, orders, and
// issued certificates are durably persisted across restarts. Nonces
// remain in-memory.
func (s *Server) AttachStorage(fs Storage) error {
if err := s.state.LoadFromStorage(fs); err != nil {
return err
}
s.certStore = NewCertStore(fs)
// Re-hydrate the in-memory cert cache for already-issued orders.
s.state.mu.Lock()
defer s.state.mu.Unlock()
for _, o := range s.state.orders {
if o.CertificateID == "" {
continue
}
der, err := s.certStore.Get(o.CertificateID)
if err != nil {
continue
}
s.certs[o.CertificateID] = der
}
return nil
}
func (s *Server) handleDirectory(w http.ResponseWriter, r *http.Request) {
d := Directory{
NewNonce: s.urlFor("/new-nonce"),
NewAccount: s.urlFor("/new-account"),
NewOrder: s.urlFor("/new-order"),
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(d)
}
func (s *Server) issueNonce(w http.ResponseWriter) {
w.Header().Set("Replay-Nonce", s.state.NewNonce())
w.Header().Set("Cache-Control", "no-store")
}
func (s *Server) handleNewNonce(w http.ResponseWriter, r *http.Request) {
s.issueNonce(w)
if r.Method == http.MethodGet {
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusOK)
}
}
// MaxJWSBytes caps the size of an incoming JWS request body. ACME
// requests are small (a few hundred bytes plus a CSR for finalize); a
// CSR for an extreme SAN list is bounded too. 256 KiB covers anything
// reasonable and refuses the rest before allocating.
const MaxJWSBytes = 256 * 1024
// jwsError carries the ACME problem document fields readJWS wants to
// surface to the handler — distinct error types per RFC 8555 §6.
type jwsError struct {
Status int
Type string
Detail string
Algorithms []string
}
func (e *jwsError) Error() string { return e.Detail }
// readJWS reads the request body, parses+verifies the JWS against either
// the embedded jwk or the looked-up account key, validates the
// protected `url` header (§6.4), consumes the nonce (§6.5), and
// returns the parsed result. Errors are *jwsError values whose Type
// is the ACME problem-document type that should be returned.
func (s *Server) readJWS(r *http.Request, expectKnownAccount bool) (*ParsedJWS, *account, error) {
// §6.2: POST must use application/jose+json; reject with 415.
ct := r.Header.Get("Content-Type")
if i := strings.IndexByte(ct, ';'); i >= 0 {
ct = strings.TrimSpace(ct[:i])
}
if !strings.EqualFold(ct, "application/jose+json") {
return nil, nil, &jwsError{
Status: http.StatusUnsupportedMediaType,
Type: "urn:ietf:params:acme:error:malformed",
Detail: fmt.Sprintf("Content-Type must be application/jose+json, got %q", ct),
}
}
r.Body = http.MaxBytesReader(nil, r.Body, MaxJWSBytes)
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, nil, &jwsError{Status: http.StatusBadRequest, Type: "urn:ietf:params:acme:error:malformed", Detail: "read body: " + err.Error()}
}
hdrPeek, err := peekJOSEHeader(body)
if err != nil {
return nil, nil, &jwsError{Status: http.StatusBadRequest, Type: "urn:ietf:params:acme:error:malformed", Detail: err.Error()}
}
// §6.2: if alg is unsupported, return badSignatureAlgorithm with
// the supported `algorithms` list. We pre-check here so the error
// type is right (otherwise jose.ParseSigned just returns "unsupported").
if hdrPeek.Alg != "" && !algSupported(hdrPeek.Alg) {
return nil, nil, &jwsError{
Status: http.StatusBadRequest,
Type: "urn:ietf:params:acme:error:badSignatureAlgorithm",
Detail: fmt.Sprintf("alg %q not supported", hdrPeek.Alg),
Algorithms: supportedAlgsList(),
}
}
var acct *account
var key *jose.JSONWebKey
if hdrPeek.KID != "" {
thumb, err := s.thumbprintFromKID(hdrPeek.KID)
if err != nil {
return nil, nil, &jwsError{Status: http.StatusBadRequest, Type: "urn:ietf:params:acme:error:malformed", Detail: err.Error()}
}
s.state.mu.Lock()
acct = s.state.accounts[thumb]
s.state.mu.Unlock()
if acct == nil {
return nil, nil, &jwsError{Status: http.StatusBadRequest, Type: "urn:ietf:params:acme:error:accountDoesNotExist", Detail: "unknown account: " + thumb}
}
var jwk jose.JSONWebKey
if err := jwk.UnmarshalJSON(acct.JWKBytes); err != nil {
return nil, nil, &jwsError{Status: http.StatusInternalServerError, Type: "urn:ietf:params:acme:error:serverInternal", Detail: "parse stored jwk: " + err.Error()}
}
key = &jwk
} else if expectKnownAccount {
return nil, nil, &jwsError{Status: http.StatusBadRequest, Type: "urn:ietf:params:acme:error:malformed", Detail: "kid required"}
}
parsed, err := ParseAndVerify(body, key)
if err != nil {
return nil, nil, &jwsError{Status: http.StatusBadRequest, Type: "urn:ietf:params:acme:error:malformed", Detail: err.Error()}
}
// §6.4: url header must equal the request URL.
if want := s.urlFor(r.URL.Path); parsed.URL != want {
return nil, nil, &jwsError{
Status: http.StatusUnauthorized,
Type: "urn:ietf:params:acme:error:unauthorized",
Detail: fmt.Sprintf("JWS url %q does not match request URL %q", parsed.URL, want),
}
}
// §6.5: nonce must validate.
if !s.state.ConsumeNonce(parsed.Nonce) {
return nil, nil, &jwsError{
Status: http.StatusBadRequest,
Type: "urn:ietf:params:acme:error:badNonce",
Detail: "nonce missing, replayed, or expired",
}
}
return parsed, acct, nil
}
// writeJWSError converts an error returned from readJWS into the
// appropriate ACME problem document. Non-jwsError values (programmer
// bugs) fall through to a 400 malformed.
func (s *Server) writeJWSError(w http.ResponseWriter, err error) {
var je *jwsError
if errors.As(err, &je) {
s.problemFull(w, je.Status, je.Type, je.Detail, je.Algorithms)
return
}
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:malformed", err.Error())
}
// algSupported reports whether `alg` is in our accepted set.
func algSupported(alg string) bool {
for _, a := range AcceptedJWSAlgs {
if string(a) == alg {
return true
}
}
return false
}
// supportedAlgsList returns the AcceptedJWSAlgs as plain strings, for
// the badSignatureAlgorithm `algorithms` field.
func supportedAlgsList() []string {
out := make([]string, 0, len(AcceptedJWSAlgs))
for _, a := range AcceptedJWSAlgs {
out = append(out, string(a))
}
return out
}
// thumbprintFromKID extracts the account thumbprint from a kid URL of
// the form ${ExternalURL}/account/${thumbprint}.
func (s *Server) thumbprintFromKID(kid string) (string, error) {
u, err := url.Parse(kid)
if err != nil {
return "", err
}
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
if len(parts) < 2 || parts[len(parts)-2] != "account" {
return "", fmt.Errorf("kid not an account URL: %q", kid)
}
return parts[len(parts)-1], nil
}
// peekedHeader carries the protected-header fields cactus uses to
// route a JWS request before verifying its signature.
type peekedHeader struct {
KID string
Alg string
}
// peekJOSEHeader extracts kid + alg (if any) from a JWS body without
// signature verification. Used so readJWS can look up the account key
// and pre-check the signature algorithm.
func peekJOSEHeader(body []byte) (peekedHeader, error) {
var v struct {
Protected string `json:"protected"`
}
if err := json.Unmarshal(body, &v); err == nil && v.Protected != "" {
raw, err := base64.RawURLEncoding.DecodeString(v.Protected)
if err != nil {
return peekedHeader{}, err
}
var hdr struct {
KID string `json:"kid"`
Alg string `json:"alg"`
}
if err := json.Unmarshal(raw, &hdr); err == nil {
return peekedHeader{KID: hdr.KID, Alg: hdr.Alg}, nil
}
}
// JWS Compact form: base64(header).base64(payload).base64(sig)
parts := strings.Split(strings.TrimSpace(string(body)), ".")
if len(parts) == 3 {
raw, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return peekedHeader{}, err
}
var hdr struct {
KID string `json:"kid"`
Alg string `json:"alg"`
}
if err := json.Unmarshal(raw, &hdr); err == nil {
return peekedHeader{KID: hdr.KID, Alg: hdr.Alg}, nil
}
}
return peekedHeader{}, nil
}
func (s *Server) handleNewAccount(w http.ResponseWriter, r *http.Request) {
parsed, _, err := s.readJWS(r, false)
if err != nil {
s.writeJWSError(w, err)
return
}
if parsed.JWK == nil {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:malformed", "new-account must use jwk header")
return
}
var req NewAccountReq
if len(parsed.Payload) > 0 {
if err := json.Unmarshal(parsed.Payload, &req); err != nil {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:malformed", "bad payload")
return
}
}
jwkBytes, err := parsed.JWK.MarshalJSON()
if err != nil {
s.problem(w, http.StatusInternalServerError, "urn:ietf:params:acme:error:serverInternal", err.Error())
return
}
acct, created, err := s.state.GetOrCreateAccount(parsed.Thumbprint, jwkBytes, req.Contact, !req.OnlyReturnExisting)
if err != nil {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:accountDoesNotExist", err.Error())
return
}
loc := s.urlFor("/account/" + acct.ID)
w.Header().Set("Location", loc)
s.issueNonce(w)
s.setIndexLink(w)
w.Header().Set("Content-Type", "application/json")
if created {
w.WriteHeader(http.StatusCreated)
} else {
w.WriteHeader(http.StatusOK)
}
_ = json.NewEncoder(w).Encode(s.accountJSON(acct))
}
// accountJSON builds the RFC 8555 §7.1.2 account object, including the
// required `orders` URL.
func (s *Server) accountJSON(acct *account) AccountResp {
return AccountResp{
Status: acct.Status,
Contact: acct.Contact,
Orders: s.urlFor("/account/" + acct.ID + "/orders"),
}
}
// handleAccount serves the account resource (RFC 8555 §7.1.2). It
// supports POST-as-GET; account update/deactivation is out of scope for
// this test server, so a non-empty payload is accepted but ignored.
func (s *Server) handleAccount(w http.ResponseWriter, r *http.Request) {
_, acct, err := s.readJWS(r, true)
if err != nil {
s.writeJWSError(w, err)
return
}
if r.PathValue("id") != acct.ID {
s.problem(w, http.StatusUnauthorized, "urn:ietf:params:acme:error:unauthorized",
"account does not match the authenticated key")
return
}
s.issueNonce(w)
s.setIndexLink(w)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(s.accountJSON(acct))
}
// handleAccountOrders serves the orders list for an account
// (RFC 8555 §7.1.2.1), as a POST-as-GET resource.
func (s *Server) handleAccountOrders(w http.ResponseWriter, r *http.Request) {
_, acct, err := s.readJWS(r, true)
if err != nil {
s.writeJWSError(w, err)
return
}
if r.PathValue("id") != acct.ID {
s.problem(w, http.StatusUnauthorized, "urn:ietf:params:acme:error:unauthorized",
"account does not match the authenticated key")
return
}
ids := s.state.OrderIDsForAccount(acct.ID)
urls := make([]string, 0, len(ids))
for _, id := range ids {
// RFC 8555 §7.1.2.1: the list SHOULD NOT include invalid orders.
// Also skip any dangling ID whose order no longer exists.
o, ok := s.state.GetOrder(id)
if !ok || o.Status == "invalid" {
continue
}
urls = append(urls, s.urlFor("/order/"+id))
}
s.issueNonce(w)
s.setIndexLink(w)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(OrdersList{Orders: urls})
}
func (s *Server) handleNewOrder(w http.ResponseWriter, r *http.Request) {
parsed, acct, err := s.readJWS(r, true)
if err != nil {
s.writeJWSError(w, err)
return
}
var req NewOrderReq
if err := json.Unmarshal(parsed.Payload, &req); err != nil {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:malformed", "bad payload")
return
}
if len(req.Identifiers) == 0 {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:malformed", "no identifiers")
return
}
// Cap to a small number so a single request can't allocate
// thousands of authz/challenge records.
const MaxIdentifiersPerOrder = 100
if len(req.Identifiers) > MaxIdentifiersPerOrder {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:malformed",
fmt.Sprintf("too many identifiers (%d > %d)", len(req.Identifiers), MaxIdentifiersPerOrder))
return
}
// Build the order, one authz/challenge per identifier.
now := time.Now().UTC()
o := &order{
ID: newID(),
AccountID: acct.ID,
Status: "pending",
Expires: now.Add(s.cfg.OrderLifetime),
Identifiers: req.Identifiers,
}
if req.NotBefore != "" {
t, err := time.Parse(time.RFC3339, req.NotBefore)
if err != nil {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:malformed",
"notBefore is not a valid RFC 3339 timestamp")
return
}
o.NotBefore = t
}
if req.NotAfter != "" {
t, err := time.Parse(time.RFC3339, req.NotAfter)
if err != nil {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:malformed",
"notAfter is not a valid RFC 3339 timestamp")
return
}
o.NotAfter = t
}
for _, id := range req.Identifiers {
switch id.Type {
case "dns":
if !validDNSName(id.Value) {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:rejectedIdentifier",
fmt.Sprintf("not a valid DNS name: %q", id.Value))
return
}
case "ip":
if net.ParseIP(id.Value) == nil {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:malformed", "bad IP identifier")
return
}
default:
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:rejectedIdentifier",
fmt.Sprintf("unsupported identifier type %q", id.Type))
return
}
ch := &challenge{
ID: newID(),
Type: "http-01",
Status: "pending",
Token: randomToken(),
}
az := &authz{
ID: newID(),
OrderID: o.ID,
Status: "pending",
Identifier: id,
ChallIDs: []string{ch.ID},
}
ch.AuthzID = az.ID
s.state.PutChallenge(ch)
s.state.PutAuthz(az)
o.AuthzIDs = append(o.AuthzIDs, az.ID)
}
// Auto-pass: instantly mark all challenges and authzs valid. Each
// state.Update* takes the same mutex, so we must release the
// authz lock before acquiring the challenge lock.
if s.cfg.ChallengeMode == ChallengeAutoPass {
now := time.Now().UTC()
for _, aid := range o.AuthzIDs {
var challIDs []string
s.state.UpdateAuthz(aid, func(a *authz) {
a.Status = "valid"
a.Expires = now.Add(s.cfg.OrderLifetime)
challIDs = append([]string(nil), a.ChallIDs...)
})
for _, cid := range challIDs {
s.state.UpdateChallenge(cid, func(c *challenge) {
c.Status = "valid"
c.Validated = now
})
}
}
o.Status = "ready"
}
s.state.PutOrder(o)
loc := s.urlFor("/order/" + o.ID)
w.Header().Set("Location", loc)
s.issueNonce(w)
s.setIndexLink(w)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(s.orderJSON(o))
}
func (s *Server) orderJSON(o *order) OrderResp {
resp := OrderResp{
Status: o.Status,
Identifiers: o.Identifiers,
Finalize: s.urlFor("/finalize/" + o.ID),
Expires: o.Expires.Format(time.RFC3339),
}
if !o.NotBefore.IsZero() {
resp.NotBefore = o.NotBefore.Format(time.RFC3339)
}
if !o.NotAfter.IsZero() {
resp.NotAfter = o.NotAfter.Format(time.RFC3339)
}
for _, aid := range o.AuthzIDs {
resp.Authorizations = append(resp.Authorizations, s.urlFor("/authz/"+aid))
}
if o.CertificateID != "" {
resp.Certificate = s.urlFor("/cert/" + o.CertificateID)
}
if o.Error != nil {
resp.Error = o.Error
}
return resp
}
// challengeMsg renders a challenge as its wire object, including the
// `validated` timestamp on valid challenges (RFC 8555 §8) and the
// `error` problem document on invalid ones.
func (s *Server) challengeMsg(c *challenge) ChallengeMsg {
msg := ChallengeMsg{
Type: c.Type,
Status: c.Status,
URL: s.urlFor("/chall/" + c.ID),
Token: c.Token,
}
if c.Status == "valid" && !c.Validated.IsZero() {
msg.Validated = c.Validated.UTC().Format(time.RFC3339)
}
if c.Status == "invalid" {
msg.Error = c.Error
}
return msg
}
func (s *Server) handleAuthz(w http.ResponseWriter, r *http.Request) {
_, acct, err := s.readJWS(r, true)
if err != nil {
s.writeJWSError(w, err)
return
}
id := r.PathValue("id")
a, ok := s.state.GetAuthz(id)
// RFC 8555 §6.3 access control; report a foreign authz as not found.
if !ok || !s.authzOwnedBy(a, acct.ID) {
s.problem(w, http.StatusNotFound, "urn:ietf:params:acme:error:malformed", "no authz")
return
}
resp := AuthzResp{
Status: a.Status,
Identifier: a.Identifier,
}
if a.Status == "valid" && !a.Expires.IsZero() {
resp.Expires = a.Expires.UTC().Format(time.RFC3339)
}
for _, cid := range a.ChallIDs {
c, ok := s.state.GetChallenge(cid)
if !ok {
continue
}
resp.Challenges = append(resp.Challenges, s.challengeMsg(c))
}
s.issueNonce(w)
s.setIndexLink(w)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
func (s *Server) handleChallenge(w http.ResponseWriter, r *http.Request) {
_, acct, err := s.readJWS(r, true)
if err != nil {
s.writeJWSError(w, err)
return
}
id := r.PathValue("id")
c, ok := s.state.GetChallenge(id)
// RFC 8555 §6.3 access control; report a foreign challenge as not
// found. This also prevents driving validation of another account's
// challenge with the caller's key authorization.
if !ok || !s.challengeOwnedBy(c, acct.ID) {
s.problem(w, http.StatusNotFound, "urn:ietf:params:acme:error:malformed", "no challenge")
return
}
if s.cfg.ChallengeMode == ChallengeHTTP01 && c.Status == "pending" {
az, ok := s.state.GetAuthz(c.AuthzID)
if !ok {
s.problem(w, http.StatusInternalServerError, "urn:ietf:params:acme:error:serverInternal", "authz missing")
return
}
if err := s.attemptHTTP01(c, az, acct); err != nil {
prob := &Problem{
Type: "urn:ietf:params:acme:error:incorrectResponse",
Detail: err.Error(),
Status: http.StatusForbidden,
}
s.state.UpdateChallenge(c.ID, func(ch *challenge) {
ch.Status = "invalid"
ch.Error = prob
})
s.problem(w, prob.Status, prob.Type, prob.Detail)
return
}
now := time.Now().UTC()
s.state.UpdateChallenge(c.ID, func(ch *challenge) {
ch.Status = "valid"
ch.Validated = now
})
// Authz is valid if any of its challenges is valid.
s.state.UpdateAuthz(az.ID, func(a *authz) {
a.Status = "valid"
a.Expires = now.Add(s.cfg.OrderLifetime)
})
// Order moves to ready when all authzs are valid.
s.maybeOrderReady(az.OrderID)
// Refresh c after the update.
c, _ = s.state.GetChallenge(c.ID)
}
s.issueNonce(w)
s.setIndexLink(w)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(s.challengeMsg(c))
}
// attemptHTTP01 fetches http://{identifier}/.well-known/acme-challenge/{token}
// and verifies the body equals the JWS-keyAuthorization. Identifier
// values are validated by validDNSName before reaching here, so the
// host isn't attacker-controlled in a way that could inject path/query
// segments into the URL.
func (s *Server) attemptHTTP01(c *challenge, az *authz, acct *account) error {
if az.Identifier.Type != "dns" {
return fmt.Errorf("http-01 only supports dns identifiers, got %q", az.Identifier.Type)
}
if !validDNSName(az.Identifier.Value) {
return fmt.Errorf("http-01 identifier %q is not a valid DNS name", az.Identifier.Value)
}
expected, err := keyAuthorization(c.Token, acct.JWKBytes)
if err != nil {
return err
}
target := (&url.URL{
Scheme: "http",
Host: az.Identifier.Value,
Path: "/.well-known/acme-challenge/" + c.Token,
}).String()
client := &http.Client{
Timeout: 5 * time.Second,
// Refuse redirects: ACME http-01 has no need to follow
// arbitrary 3xx, and following them is a small SSRF amplifier.
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Get(target)
if err != nil {
return fmt.Errorf("fetch challenge: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("challenge URL returned %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, 4096))
if err != nil {
return err
}
got := strings.TrimSpace(string(body))
if got != expected {
return fmt.Errorf("body %q != expected %q", got, expected)
}
return nil
}
// validDNSName reports whether name is a syntactically valid DNS name
// (RFC 1035 letters-digits-hyphen, dotted, no leading/trailing dots,
// labels 1–63 chars, total ≤253 chars). An optional ":port" suffix
// where port is all digits is allowed, so that auto-pass / http-01
// tests can bind on non-default ports without opening the door to
// path/query/fragment injection (e.g. "evil.com:80/foo?x=" is
// rejected because "80/foo?x=" isn't all digits).
func validDNSName(name string) bool {
if len(name) == 0 {
return false
}
if i := strings.LastIndexByte(name, ':'); i >= 0 {
port := name[i+1:]
if len(port) == 0 || len(port) > 5 {
return false
}
for j := 0; j < len(port); j++ {
if port[j] < '0' || port[j] > '9' {
return false
}
}
name = name[:i]
}
if len(name) == 0 || len(name) > 253 {
return false
}
if name[0] == '.' || name[len(name)-1] == '.' {
return false
}
for _, label := range strings.Split(name, ".") {
if len(label) == 0 || len(label) > 63 {
return false
}
if label[0] == '-' || label[len(label)-1] == '-' {
return false
}
for i := 0; i < len(label); i++ {
b := label[i]
ok := (b >= 'a' && b <= 'z') ||
(b >= 'A' && b <= 'Z') ||
(b >= '0' && b <= '9') ||
b == '-' || b == '_'
if !ok {
return false
}
}
}
return true
}
// maybeOrderReady transitions an order to "ready" if all its authzs
// are valid.
func (s *Server) maybeOrderReady(orderID string) {
o, ok := s.state.GetOrder(orderID)
if !ok || o.Status != "pending" {
return
}
allValid := true
for _, aid := range o.AuthzIDs {
az, ok := s.state.GetAuthz(aid)
if !ok || az.Status != "valid" {
allValid = false
break
}
}
if allValid {
s.state.UpdateOrder(o.ID, func(o *order) { o.Status = "ready" })
}
}
func (s *Server) handleOrder(w http.ResponseWriter, r *http.Request) {
_, acct, err := s.readJWS(r, true)
if err != nil {
s.writeJWSError(w, err)
return
}
id := r.PathValue("id")
o, ok := s.state.GetOrder(id)
// RFC 8555 §6.3: enforce access control. A mismatch is reported as
// "not found" so an unrelated account can't probe order existence.
if !ok || o.AccountID != acct.ID {
s.problem(w, http.StatusNotFound, "urn:ietf:params:acme:error:malformed", "no order")
return
}
s.issueNonce(w)
s.setIndexLink(w)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(s.orderJSON(o))
}
func (s *Server) handleFinalize(w http.ResponseWriter, r *http.Request) {
parsed, acct, err := s.readJWS(r, true)
if err != nil {
s.writeJWSError(w, err)
return
}
id := r.PathValue("id")
// Parse and validate the request body and CSR before mutating any
// order state, so a malformed finalize can never strand the order
// in "processing" (RFC 8555 §7.1.6: a processing order only advances
// to valid/invalid, so the client could otherwise never retry).
var req FinalizeReq
if err := json.Unmarshal(parsed.Payload, &req); err != nil {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:malformed", "bad payload")
return
}
csrDER, err := base64.RawURLEncoding.DecodeString(req.CSR)
if err != nil {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:badCSR", "csr not base64url")
return
}
csr, err := x509.ParseCertificateRequest(csrDER)
if err != nil {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:badCSR", err.Error())
return
}
// RFC 8555 §11.1: the CSR public key MUST differ from the account key.
if acctKey, kerr := s.accountPublicKey(acct); kerr == nil && samePublicKey(csr.PublicKey, acctKey) {
s.problem(w, http.StatusBadRequest, "urn:ietf:params:acme:error:badCSR",
"CSR public key must not equal the account key")
return
}
// RFC 8555 §6.3 access control: the order must belong to the
// authenticated account. AccountID is immutable, so checking before
// the atomic claim below is sufficient. Report a foreign order as
// "not found" rather than disclosing its existence.
if o, ok := s.state.GetOrder(id); !ok || o.AccountID != acct.ID {
s.problem(w, http.StatusNotFound, "urn:ietf:params:acme:error:malformed", "no order")
return
}
// Atomic ready→processing claim. The loser of a finalize race
// gets "orderNotReady"; the order remains valid because the winner
// will produce the cert.
o, claimed := s.state.TryClaimReadyOrder(id)
if o == nil {
s.problem(w, http.StatusNotFound, "urn:ietf:params:acme:error:malformed", "no order")
return
}
if !claimed {
s.problem(w, http.StatusForbidden, "urn:ietf:params:acme:error:orderNotReady",
fmt.Sprintf("order is %s", o.Status))
return
}
// Build the order input from the (already-validated) order.
orderInput := ca.OrderInput{
NotBefore: o.NotBefore,
NotAfter: o.NotAfter,
}
for _, idn := range o.Identifiers {
switch idn.Type {
case "dns":
orderInput.AuthorizedDNSNames = append(orderInput.AuthorizedDNSNames, idn.Value)
case "ip":
ip := net.ParseIP(idn.Value)
if ip != nil {
orderInput.AuthorizedIPs = append(orderInput.AuthorizedIPs, ip)
}
}
}
// Issue (this calls log.Append + Wait).
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
der, err := s.cfg.Issuer.Issue(ctx, csr, orderInput)
if err != nil {
// CSR/order mismatches surface as ca.ErrBadCSR; map to the
// RFC 8555 §7.4 badCSR error type, otherwise serverInternal.
prob := &Problem{
Type: "urn:ietf:params:acme:error:serverInternal",
Detail: err.Error(),
Status: http.StatusInternalServerError,
}
if errors.Is(err, ca.ErrBadCSR) {
prob.Type = "urn:ietf:params:acme:error:badCSR"
prob.Status = http.StatusBadRequest
}
// Record the error on the order (RFC 8555 §7.1.6: an invalid
// order SHOULD carry an error problem document).
s.state.UpdateOrder(o.ID, func(o *order) {
o.Status = "invalid"
o.Error = prob
})
if s.cfg.OrdersByStatus != nil {
s.cfg.OrdersByStatus.WithLabelValues("invalid").Add(1)
}
s.problem(w, prob.Status, prob.Type, prob.Detail)
return
}
certID := newID()
s.state.UpdateOrder(o.ID, func(o *order) {
o.Status = "valid"