-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathra.go
2009 lines (1821 loc) · 71.7 KB
/
ra.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 ra
import (
"crypto/x509"
"fmt"
"net"
"net/mail"
"net/url"
"reflect"
"sort"
"strings"
"time"
"github.com/jmhodges/clock"
"github.com/letsencrypt/boulder/akamai"
akamaipb "github.com/letsencrypt/boulder/akamai/proto"
caPB "github.com/letsencrypt/boulder/ca/proto"
"github.com/letsencrypt/boulder/core"
corepb "github.com/letsencrypt/boulder/core/proto"
csrlib "github.com/letsencrypt/boulder/csr"
"github.com/letsencrypt/boulder/ctpolicy"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/features"
"github.com/letsencrypt/boulder/goodkey"
bgrpc "github.com/letsencrypt/boulder/grpc"
"github.com/letsencrypt/boulder/iana"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/metrics"
"github.com/letsencrypt/boulder/probs"
rapb "github.com/letsencrypt/boulder/ra/proto"
"github.com/letsencrypt/boulder/ratelimit"
"github.com/letsencrypt/boulder/reloader"
"github.com/letsencrypt/boulder/revocation"
sapb "github.com/letsencrypt/boulder/sa/proto"
vaPB "github.com/letsencrypt/boulder/va/proto"
"github.com/letsencrypt/boulder/web"
"github.com/prometheus/client_golang/prometheus"
"github.com/weppos/publicsuffix-go/publicsuffix"
"golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
type caaChecker interface {
IsCAAValid(
ctx context.Context,
in *vaPB.IsCAAValidRequest,
opts ...grpc.CallOption,
) (*vaPB.IsCAAValidResponse, error)
}
// RegistrationAuthorityImpl defines an RA.
//
// NOTE: All of the fields in RegistrationAuthorityImpl need to be
// populated, or there is a risk of panic.
type RegistrationAuthorityImpl struct {
CA core.CertificateAuthority
VA core.ValidationAuthority
SA core.StorageAuthority
PA core.PolicyAuthority
publisher core.Publisher
caa caaChecker
stats metrics.Scope
clk clock.Clock
log blog.Logger
keyPolicy goodkey.KeyPolicy
// How long before a newly created authorization expires.
authorizationLifetime time.Duration
pendingAuthorizationLifetime time.Duration
rlPolicies ratelimit.Limits
maxContactsPerReg int
maxNames int
forceCNFromSAN bool
reuseValidAuthz bool
orderLifetime time.Duration
issuer *x509.Certificate
purger akamaipb.AkamaiPurgerClient
regByIPStats metrics.Scope
regByIPRangeStats metrics.Scope
pendAuthByRegIDStats metrics.Scope
pendOrdersByRegIDStats metrics.Scope
newOrderByRegIDStats metrics.Scope
certsForDomainStats metrics.Scope
ctpolicy *ctpolicy.CTPolicy
ctpolicyResults *prometheus.HistogramVec
}
// NewRegistrationAuthorityImpl constructs a new RA object.
func NewRegistrationAuthorityImpl(
clk clock.Clock,
logger blog.Logger,
stats metrics.Scope,
maxContactsPerReg int,
keyPolicy goodkey.KeyPolicy,
maxNames int,
forceCNFromSAN bool,
reuseValidAuthz bool,
authorizationLifetime time.Duration,
pendingAuthorizationLifetime time.Duration,
pubc core.Publisher,
caaClient caaChecker,
orderLifetime time.Duration,
ctp *ctpolicy.CTPolicy,
purger akamaipb.AkamaiPurgerClient,
issuer *x509.Certificate,
) *RegistrationAuthorityImpl {
ctpolicyResults := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "ctpolicy_results",
Help: "Histogram of latencies of ctpolicy.GetSCTs calls with success/failure/deadlineExceeded labels",
Buckets: metrics.InternetFacingBuckets,
},
[]string{"result"},
)
stats.MustRegister(ctpolicyResults)
ra := &RegistrationAuthorityImpl{
stats: stats,
clk: clk,
log: logger,
authorizationLifetime: authorizationLifetime,
pendingAuthorizationLifetime: pendingAuthorizationLifetime,
rlPolicies: ratelimit.New(),
maxContactsPerReg: maxContactsPerReg,
keyPolicy: keyPolicy,
maxNames: maxNames,
forceCNFromSAN: forceCNFromSAN,
reuseValidAuthz: reuseValidAuthz,
regByIPStats: stats.NewScope("RateLimit", "RegistrationsByIP"),
regByIPRangeStats: stats.NewScope("RateLimit", "RegistrationsByIPRange"),
pendAuthByRegIDStats: stats.NewScope("RateLimit", "PendingAuthorizationsByRegID"),
pendOrdersByRegIDStats: stats.NewScope("RateLimit", "PendingOrdersByRegID"),
newOrderByRegIDStats: stats.NewScope("RateLimit", "NewOrdersByRegID"),
certsForDomainStats: stats.NewScope("RateLimit", "CertificatesForDomain"),
publisher: pubc,
caa: caaClient,
orderLifetime: orderLifetime,
ctpolicy: ctp,
ctpolicyResults: ctpolicyResults,
purger: purger,
issuer: issuer,
}
return ra
}
func (ra *RegistrationAuthorityImpl) SetRateLimitPoliciesFile(filename string) error {
_, err := reloader.New(filename, ra.rlPolicies.LoadPolicies, ra.rateLimitPoliciesLoadError)
if err != nil {
return err
}
return nil
}
func (ra *RegistrationAuthorityImpl) rateLimitPoliciesLoadError(err error) {
ra.log.Errf("error reloading rate limit policy: %s", err)
}
// certificateRequestAuthz is a struct for holding information about a valid
// authz referenced during a certificateRequestEvent. It holds both the
// authorization ID and the challenge type that made the authorization valid. We
// specifically include the challenge type that solved the authorization to make
// some common analysis easier.
type certificateRequestAuthz struct {
ID string
ChallengeType string
}
// certificateRequestEvent is a struct for holding information that is logged as
// JSON to the audit log as the result of an issuance event.
type certificateRequestEvent struct {
ID string `json:",omitempty"`
// Requester is the associated account ID
Requester int64 `json:",omitempty"`
// OrderID is the associated order ID (may be empty for an ACME v1 issuance)
OrderID int64 `json:",omitempty"`
// SerialNumber is the string representation of the issued certificate's
// serial number
SerialNumber string `json:",omitempty"`
// VerifiedFields are required by the baseline requirements and are always
// a static value for Boulder.
VerifiedFields []string `json:",omitempty"`
// CommonName is the subject common name from the issued cert
CommonName string `json:",omitempty"`
// Names are the DNS SAN entries from the issued cert
Names []string `json:",omitempty"`
// NotBefore is the starting timestamp of the issued cert's validity period
NotBefore time.Time `json:",omitempty"`
// NotAfter is the ending timestamp of the issued cert's validity period
NotAfter time.Time `json:",omitempty"`
// RequestTime and ResponseTime are for tracking elapsed time during issuance
RequestTime time.Time `json:",omitempty"`
ResponseTime time.Time `json:",omitempty"`
// Error contains any encountered errors
Error string `json:",omitempty"`
// Authorizations is a map of identifier names to certificateRequestAuthz
// objects. It can be used to understand how the names in a certificate
// request were authorized.
Authorizations map[string]certificateRequestAuthz
}
// noRegistrationID is used for the regID parameter to GetThreshold when no
// registration-based overrides are necessary.
const noRegistrationID = -1
// registrationCounter is a type to abstract the use of
// ra.SA.CountRegistrationsByIP or ra.SA.CountRegistrationsByIPRange
type registrationCounter func(context.Context, net.IP, time.Time, time.Time) (int, error)
// checkRegistrationIPLimit checks a specific registraton limit by using the
// provided registrationCounter function to determine if the limit has been
// exceeded for a given IP or IP range
func (ra *RegistrationAuthorityImpl) checkRegistrationIPLimit(
ctx context.Context,
limit ratelimit.RateLimitPolicy,
ip net.IP,
counter registrationCounter) error {
if !limit.Enabled() {
return nil
}
now := ra.clk.Now()
windowBegin := limit.WindowBegin(now)
count, err := counter(ctx, ip, windowBegin, now)
if err != nil {
return err
}
if count >= limit.GetThreshold(ip.String(), noRegistrationID) {
return berrors.RateLimitError("too many registrations for this IP")
}
return nil
}
// checkRegistrationLimits enforces the RegistrationsPerIP and
// RegistrationsPerIPRange limits
func (ra *RegistrationAuthorityImpl) checkRegistrationLimits(ctx context.Context, ip net.IP) error {
// Check the registrations per IP limit using the CountRegistrationsByIP SA
// function that matches IP addresses exactly
exactRegLimit := ra.rlPolicies.RegistrationsPerIP()
err := ra.checkRegistrationIPLimit(ctx, exactRegLimit, ip, ra.SA.CountRegistrationsByIP)
if err != nil {
ra.regByIPStats.Inc("Exceeded", 1)
ra.log.Infof("Rate limit exceeded, RegistrationsByIP, IP: %s", ip)
return err
}
ra.regByIPStats.Inc("Pass", 1)
// We only apply the fuzzy reg limit to IPv6 addresses.
// Per https://golang.org/pkg/net/#IP.To4 "If ip is not an IPv4 address, To4
// returns nil"
if ip.To4() != nil {
return nil
}
// Check the registrations per IP range limit using the
// CountRegistrationsByIPRange SA function that fuzzy-matches IPv6 addresses
// within a larger address range
fuzzyRegLimit := ra.rlPolicies.RegistrationsPerIPRange()
err = ra.checkRegistrationIPLimit(ctx, fuzzyRegLimit, ip, ra.SA.CountRegistrationsByIPRange)
if err != nil {
ra.regByIPRangeStats.Inc("Exceeded", 1)
ra.log.Infof("Rate limit exceeded, RegistrationsByIPRange, IP: %s", ip)
// For the fuzzyRegLimit we use a new error message that specifically
// mentions that the limit being exceeded is applied to a *range* of IPs
return berrors.RateLimitError("too many registrations for this IP range")
}
ra.regByIPRangeStats.Inc("Pass", 1)
return nil
}
// NewRegistration constructs a new Registration from a request.
func (ra *RegistrationAuthorityImpl) NewRegistration(ctx context.Context, init core.Registration) (core.Registration, error) {
if err := ra.keyPolicy.GoodKey(init.Key.Key); err != nil {
return core.Registration{}, berrors.MalformedError("invalid public key: %s", err.Error())
}
if err := ra.checkRegistrationLimits(ctx, init.InitialIP); err != nil {
return core.Registration{}, err
}
reg := core.Registration{
Key: init.Key,
Status: core.StatusValid,
}
_ = mergeUpdate(®, init)
// This field isn't updatable by the end user, so it isn't copied by
// MergeUpdate. But we need to fill it in for new registrations.
reg.InitialIP = init.InitialIP
if err := ra.validateContacts(ctx, reg.Contact); err != nil {
return core.Registration{}, err
}
// Store the authorization object, then return it
reg, err := ra.SA.NewRegistration(ctx, reg)
if err != nil {
return core.Registration{}, err
}
ra.stats.Inc("NewRegistrations", 1)
return reg, nil
}
// validateContacts checks the provided list of contacts, returning an error if
// any are not acceptable. Unacceptable contacts lists include:
// * An empty list
// * A list has more than maxContactsPerReg contacts
// * A list containing an empty contact
// * A list containing a contact that does not parse as a URL
// * A list containing a contact that has a URL scheme other than mailto
// * A list containing a contact that has non-ascii characters
// * A list containing a contact that doesn't pass `validateEmail`
func (ra *RegistrationAuthorityImpl) validateContacts(ctx context.Context, contacts *[]string) error {
if contacts == nil || len(*contacts) == 0 {
return nil // Nothing to validate
}
if ra.maxContactsPerReg > 0 && len(*contacts) > ra.maxContactsPerReg {
return berrors.MalformedError(
"too many contacts provided: %d > %d",
len(*contacts),
ra.maxContactsPerReg,
)
}
for _, contact := range *contacts {
if contact == "" {
return berrors.MalformedError("empty contact")
}
parsed, err := url.Parse(contact)
if err != nil {
return berrors.MalformedError("invalid contact")
}
if parsed.Scheme != "mailto" {
return berrors.MalformedError("contact method %s is not supported", parsed.Scheme)
}
if !core.IsASCII(contact) {
return berrors.MalformedError(
"contact email [%s] contains non-ASCII characters",
contact,
)
}
if err := validateEmail(parsed.Opaque); err != nil {
return err
}
}
return nil
}
var (
// unparseableEmailError is returned by validateEmail when the given address
// is not parseable.
unparseableEmailError = berrors.InvalidEmailError("not a valid e-mail address")
)
// forbiddenMailDomains is a map of domain names we do not allow after the
// @ symbol in contact mailto addresses. These are frequently used when
// copy-pasting example configurations and would not result in expiration
// messages and subscriber communications reaching the user that created the
// registration if allowed.
var forbiddenMailDomains = map[string]bool{
// https://tools.ietf.org/html/rfc2606#section-3
"example.com": true,
"example.net": true,
"example.org": true,
}
// validateEmail returns an error if the given address is not parseable as an
// email address or if the domain portion of the email address is a member of
// the forbiddenMailDomains map.
func validateEmail(address string) error {
email, err := mail.ParseAddress(address)
if err != nil {
return unparseableEmailError
}
splitEmail := strings.SplitN(email.Address, "@", -1)
domain := strings.ToLower(splitEmail[len(splitEmail)-1])
if forbiddenMailDomains[domain] {
return berrors.InvalidEmailError(
"invalid contact domain. Contact emails @%s are forbidden",
domain)
}
if _, err := iana.ExtractSuffix(domain); err != nil {
return berrors.InvalidEmailError("email domain name does not end in a IANA suffix")
}
return nil
}
func (ra *RegistrationAuthorityImpl) checkPendingAuthorizationLimit(ctx context.Context, regID int64) error {
limit := ra.rlPolicies.PendingAuthorizationsPerAccount()
if limit.Enabled() {
count, err := ra.SA.CountPendingAuthorizations(ctx, regID)
if err != nil {
return err
}
// Most rate limits have a key for overrides, but there is no meaningful key
// here.
noKey := ""
if count >= limit.GetThreshold(noKey, regID) {
ra.pendAuthByRegIDStats.Inc("Exceeded", 1)
ra.log.Infof("Rate limit exceeded, PendingAuthorizationsByRegID, regID: %d", regID)
return berrors.RateLimitError("too many currently pending authorizations")
}
ra.pendAuthByRegIDStats.Inc("Pass", 1)
}
return nil
}
func (ra *RegistrationAuthorityImpl) checkInvalidAuthorizationLimit(ctx context.Context, regID int64, hostname string) error {
limit := ra.rlPolicies.InvalidAuthorizationsPerAccount()
// The SA.CountInvalidAuthorizations method is not implemented on the wrapper
// interface, because we want to move towards using gRPC interfaces more
// directly. So we type-assert the wrapper to a gRPC-specific type.
saGRPC, ok := ra.SA.(*bgrpc.StorageAuthorityClientWrapper)
if !limit.Enabled() || !ok {
return nil
}
latest := ra.clk.Now().Add(ra.pendingAuthorizationLifetime)
earliest := latest.Add(-limit.Window.Duration)
latestNanos := latest.UnixNano()
earliestNanos := earliest.UnixNano()
count, err := saGRPC.CountInvalidAuthorizations(ctx, &sapb.CountInvalidAuthorizationsRequest{
RegistrationID: ®ID,
Hostname: &hostname,
Range: &sapb.Range{
Earliest: &earliestNanos,
Latest: &latestNanos,
},
})
if err != nil {
return err
}
if count == nil {
return fmt.Errorf("nil count")
}
// Most rate limits have a key for overrides, but there is no meaningful key
// here.
noKey := ""
if *count.Count >= int64(limit.GetThreshold(noKey, regID)) {
ra.log.Infof("Rate limit exceeded, InvalidAuthorizationsByRegID, regID: %d", regID)
return berrors.RateLimitError("too many failed authorizations recently")
}
return nil
}
// checkNewOrdersPerAccountLimit enforces the rlPolicies `NewOrdersPerAccount`
// rate limit. This rate limit ensures a client can not create more than the
// specified threshold of new orders within the specified time window.
func (ra *RegistrationAuthorityImpl) checkNewOrdersPerAccountLimit(ctx context.Context, acctID int64) error {
limit := ra.rlPolicies.NewOrdersPerAccount()
if !limit.Enabled() {
return nil
}
latest := ra.clk.Now()
earliest := latest.Add(-limit.Window.Duration)
count, err := ra.SA.CountOrders(ctx, acctID, earliest, latest)
if err != nil {
return err
}
// There is no meaningful override key to use for this rate limit
noKey := ""
if count >= limit.GetThreshold(noKey, acctID) {
ra.newOrderByRegIDStats.Inc("Exceeded", 1)
return berrors.RateLimitError("too many new orders recently")
}
ra.newOrderByRegIDStats.Inc("Pass", 1)
return nil
}
// NewAuthorization constructs a new Authz from a request. Values (domains) in
// request.Identifier will be lowercased before storage.
func (ra *RegistrationAuthorityImpl) NewAuthorization(ctx context.Context, request core.Authorization, regID int64) (core.Authorization, error) {
identifier := request.Identifier
identifier.Value = strings.ToLower(identifier.Value)
// Check that the identifier is present and appropriate
if err := ra.PA.WillingToIssue(identifier); err != nil {
return core.Authorization{}, err
}
if err := ra.checkPendingAuthorizationLimit(ctx, regID); err != nil {
return core.Authorization{}, err
}
if err := ra.checkInvalidAuthorizationLimit(ctx, regID, identifier.Value); err != nil {
return core.Authorization{}, err
}
if ra.reuseValidAuthz {
auths, err := ra.SA.GetValidAuthorizations(ctx, regID, []string{identifier.Value}, ra.clk.Now())
if err != nil {
outErr := berrors.InternalServerError(
"unable to get existing validations for regID: %d, identifier: %s, %s",
regID,
identifier.Value,
err,
)
ra.log.Warning(outErr.Error())
return core.Authorization{}, outErr
}
if existingAuthz, ok := auths[identifier.Value]; ok {
// Use the valid existing authorization's ID to find a fully populated version
// The results from `GetValidAuthorizations` are most notably missing
// `Challenge` values that the client expects in the result.
populatedAuthz, err := ra.SA.GetAuthorization(ctx, existingAuthz.ID)
if err != nil {
outErr := berrors.InternalServerError(
"unable to get existing authorization for auth ID: %s",
existingAuthz.ID,
)
ra.log.Warningf("%s: %s", outErr.Error(), existingAuthz.ID)
return core.Authorization{}, outErr
}
if ra.authzValidChallengeEnabled(&populatedAuthz) {
// The existing authorization must not expire within the next 24 hours for
// it to be OK for reuse
reuseCutOff := ra.clk.Now().Add(time.Hour * 24)
if populatedAuthz.Expires.After(reuseCutOff) {
ra.stats.Inc("ReusedValidAuthz", 1)
return populatedAuthz, nil
}
}
}
}
nowishNano := ra.clk.Now().Add(time.Hour).UnixNano()
identifierTypeString := string(identifier.Type)
pendingAuth, err := ra.SA.GetPendingAuthorization(ctx, &sapb.GetPendingAuthorizationRequest{
RegistrationID: ®ID,
IdentifierType: &identifierTypeString,
IdentifierValue: &identifier.Value,
ValidUntil: &nowishNano,
})
if err != nil && !berrors.Is(err, berrors.NotFound) {
return core.Authorization{}, berrors.InternalServerError(
"unable to get pending authorization for regID: %d, identifier: %s: %s",
regID,
identifier.Value,
err)
} else if err == nil {
return *pendingAuth, nil
}
v2 := features.Enabled(features.NewAuthorizationSchema)
authzPB, err := ra.createPendingAuthz(ctx, regID, identifier, v2)
if err != nil {
return core.Authorization{}, err
}
if v2 {
authzIDs, err := ra.SA.NewAuthorizations2(ctx, &sapb.AddPendingAuthorizationsRequest{
Authz: []*corepb.Authorization{authzPB},
})
if err != nil {
return core.Authorization{}, err
}
if len(authzIDs.Ids) != 1 {
return core.Authorization{}, berrors.InternalServerError("unexpected number of authorization IDs returned from NewAuthorizations2: expected 1, got %d", len(authzIDs.Ids))
}
// The current internal authorization objects use a string for the ID, the new
// storage format uses a integer ID. In order to maintain compatibility we
// convert the integer ID to a string.
id := fmt.Sprintf("%d", authzIDs.Ids[0])
authzPB.Id = &id
return bgrpc.PBToAuthz(authzPB)
}
authz, err := bgrpc.PBToAuthz(authzPB)
if err != nil {
return core.Authorization{}, err
}
result, err := ra.SA.NewPendingAuthorization(ctx, authz)
if err != nil {
// berrors.InternalServerError since the user-data was validated before being
// passed to the SA.
err = berrors.InternalServerError("failed to store new pending authorization: %s", err)
return core.Authorization{}, err
}
return result, nil
}
// MatchesCSR tests the contents of a generated certificate to make sure
// that the PublicKey, CommonName, and DNSNames match those provided in
// the CSR that was used to generate the certificate. It also checks the
// following fields for:
// * notBefore is not more than 24 hours ago
// * BasicConstraintsValid is true
// * IsCA is false
// * ExtKeyUsage only contains ExtKeyUsageServerAuth & ExtKeyUsageClientAuth
// * Subject only contains CommonName & Names
func (ra *RegistrationAuthorityImpl) MatchesCSR(parsedCertificate *x509.Certificate, csr *x509.CertificateRequest) error {
// Check issued certificate matches what was expected from the CSR
hostNames := make([]string, len(csr.DNSNames))
copy(hostNames, csr.DNSNames)
if len(csr.Subject.CommonName) > 0 {
hostNames = append(hostNames, csr.Subject.CommonName)
}
hostNames = core.UniqueLowerNames(hostNames)
if !core.KeyDigestEquals(parsedCertificate.PublicKey, csr.PublicKey) {
return berrors.InternalServerError("generated certificate public key doesn't match CSR public key")
}
if !ra.forceCNFromSAN && len(csr.Subject.CommonName) > 0 &&
parsedCertificate.Subject.CommonName != strings.ToLower(csr.Subject.CommonName) {
return berrors.InternalServerError("generated certificate CommonName doesn't match CSR CommonName")
}
// Sort both slices of names before comparison.
parsedNames := parsedCertificate.DNSNames
sort.Strings(parsedNames)
sort.Strings(hostNames)
if !reflect.DeepEqual(parsedNames, hostNames) {
return berrors.InternalServerError("generated certificate DNSNames don't match CSR DNSNames")
}
if !reflect.DeepEqual(parsedCertificate.IPAddresses, csr.IPAddresses) {
return berrors.InternalServerError("generated certificate IPAddresses don't match CSR IPAddresses")
}
if !reflect.DeepEqual(parsedCertificate.EmailAddresses, csr.EmailAddresses) {
return berrors.InternalServerError("generated certificate EmailAddresses don't match CSR EmailAddresses")
}
if len(parsedCertificate.Subject.Country) > 0 || len(parsedCertificate.Subject.Organization) > 0 ||
len(parsedCertificate.Subject.OrganizationalUnit) > 0 || len(parsedCertificate.Subject.Locality) > 0 ||
len(parsedCertificate.Subject.Province) > 0 || len(parsedCertificate.Subject.StreetAddress) > 0 ||
len(parsedCertificate.Subject.PostalCode) > 0 {
return berrors.InternalServerError("generated certificate Subject contains fields other than CommonName, or SerialNumber")
}
now := ra.clk.Now()
if now.Sub(parsedCertificate.NotBefore) > time.Hour*24 {
return berrors.InternalServerError("generated certificate is back dated %s", now.Sub(parsedCertificate.NotBefore))
}
if !parsedCertificate.BasicConstraintsValid {
return berrors.InternalServerError("generated certificate doesn't have basic constraints set")
}
if parsedCertificate.IsCA {
return berrors.InternalServerError("generated certificate can sign other certificates")
}
if !reflect.DeepEqual(parsedCertificate.ExtKeyUsage, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}) {
return berrors.InternalServerError("generated certificate doesn't have correct key usage extensions")
}
return nil
}
// checkOrderAuthorizations verifies that a provided set of names associated
// with a specific order and account has all of the required valid, unexpired
// authorizations to proceed with issuance. It is the ACME v2 equivalent of
// `checkAuthorizations`. It returns the authorizations that satisfied the set
// of names or it returns an error. If it returns an error, it will be of type
// BoulderError.
func (ra *RegistrationAuthorityImpl) checkOrderAuthorizations(
ctx context.Context,
names []string,
acctID accountID,
orderID orderID) (map[string]*core.Authorization, error) {
acctIDInt := int64(acctID)
orderIDInt := int64(orderID)
// Get all of the valid authorizations for this account/order
authzs, err := ra.SA.GetValidOrderAuthorizations(
ctx,
&sapb.GetValidOrderAuthorizationsRequest{
Id: &orderIDInt,
AcctID: &acctIDInt,
})
if err != nil {
return nil, berrors.InternalServerError("error in GetValidOrderAuthorizations: %s", err)
}
// Ensure the names from the CSR are free of duplicates & lowercased.
names = core.UniqueLowerNames(names)
// Check the authorizations to ensure validity for the names required.
if err = ra.checkAuthorizationsCAA(ctx, names, authzs, acctIDInt, ra.clk.Now()); err != nil {
return nil, err
}
return authzs, nil
}
// checkAuthorizations checks that each requested name has a valid authorization
// that won't expire before the certificate expires. It returns the
// authorizations that satisifed the set of names or it returns an error.
// If it returns an error, it will be of type BoulderError.
func (ra *RegistrationAuthorityImpl) checkAuthorizations(ctx context.Context, names []string, regID int64) (map[string]*core.Authorization, error) {
now := ra.clk.Now()
for i := range names {
names[i] = strings.ToLower(names[i])
}
auths, err := ra.SA.GetValidAuthorizations(ctx, regID, names, now)
if err != nil {
return nil, berrors.InternalServerError("error in GetValidAuthorizations: %s", err)
}
if err = ra.checkAuthorizationsCAA(ctx, names, auths, regID, now); err != nil {
return nil, err
}
return auths, nil
}
// checkAuthorizationsCAA implements the common logic of validating a set of
// authorizations against a set of names that is used by both
// `checkAuthorizations` and `checkOrderAuthorizations`. If required CAA will be
// rechecked for authorizations that are too old.
// If it returns an error, it will be of type BoulderError.
func (ra *RegistrationAuthorityImpl) checkAuthorizationsCAA(
ctx context.Context,
names []string,
authzs map[string]*core.Authorization,
regID int64,
now time.Time) error {
// badNames contains the names that were unauthorized
var badNames []string
// recheckAuthzs is a list of authorizations that must have their CAA records rechecked
var recheckAuthzs []*core.Authorization
// Per Baseline Requirements, CAA must be checked within 8 hours of issuance.
// CAA is checked when an authorization is validated, so as long as that was
// less than 8 hours ago, we're fine. If it was more than 8 hours ago
// we have to recheck. Since we don't record the validation time for
// authorizations, we instead look at the expiration time and subtract out the
// expected authorization lifetime. Note: If we adjust the authorization
// lifetime in the future we will need to tweak this correspondingly so it
// works correctly during the switchover.
caaRecheckTime := now.Add(ra.authorizationLifetime).Add(-8 * time.Hour)
for _, name := range names {
authz := authzs[name]
if authz == nil {
badNames = append(badNames, name)
} else if authz.Expires == nil {
return berrors.InternalServerError("found an authorization with a nil Expires field: id %s", authz.ID)
} else if authz.Expires.Before(now) {
badNames = append(badNames, name)
} else if authz.Expires.Before(caaRecheckTime) {
// Ensure that CAA is rechecked for this name
recheckAuthzs = append(recheckAuthzs, authz)
}
}
if len(recheckAuthzs) > 0 {
if err := ra.recheckCAA(ctx, recheckAuthzs); err != nil {
return err
}
}
if len(badNames) > 0 {
return berrors.UnauthorizedError(
"authorizations for these names not found or expired: %s",
strings.Join(badNames, ", "),
)
}
return nil
}
// recheckCAA accepts a list of of names that need to have their CAA records
// rechecked because their associated authorizations are sufficiently old and
// performs the CAA checks required for each. If any of the rechecks fail an
// error is returned.
func (ra *RegistrationAuthorityImpl) recheckCAA(ctx context.Context, authzs []*core.Authorization) error {
ra.stats.Inc("recheck_caa", 1)
ra.stats.Inc("recheck_caa_authzs", int64(len(authzs)))
ch := make(chan error, len(authzs))
for _, authz := range authzs {
go func(authz *core.Authorization) {
name := authz.Identifier.Value
// If an authorization has multiple valid challenges,
// the type of the first valid challenge is used for
// the purposes of CAA rechecking.
var method string
for _, challenge := range authz.Challenges {
if challenge.Status == core.StatusValid {
method = challenge.Type
break
}
}
if method == "" {
ch <- berrors.InternalServerError(
"Internal error determining validation method for authorization ID %v (%v)",
authz.ID, name,
)
return
}
resp, err := ra.caa.IsCAAValid(ctx, &vaPB.IsCAAValidRequest{
Domain: &name,
ValidationMethod: &method,
AccountURIID: &authz.RegistrationID,
})
if err != nil {
ra.log.AuditErrf("Rechecking CAA: %s", err)
err = berrors.InternalServerError(
"Internal error rechecking CAA for authorization ID %v (%v)",
authz.ID, name,
)
} else if resp.Problem != nil {
err = berrors.CAAError(*resp.Problem.Detail)
}
ch <- err
}(authz)
}
var caaFailures []string
for _ = range authzs {
if err := <-ch; berrors.Is(err, berrors.CAA) {
caaFailures = append(caaFailures, err.Error())
} else if err != nil {
return err
}
}
if len(caaFailures) > 0 {
return berrors.CAAError("Rechecking CAA: %v", strings.Join(caaFailures, ", "))
}
return nil
}
// failOrder marks an order as failed by setting the problem details field of
// the order & persisting it through the SA. If an error occurs doing this we
// log it and return the order as-is. There aren't any alternatives if we can't
// add the error to the order.
func (ra *RegistrationAuthorityImpl) failOrder(
ctx context.Context,
order *corepb.Order,
prob *probs.ProblemDetails) *corepb.Order {
// Convert the problem to a protobuf problem for the *corepb.Order field
pbProb, err := bgrpc.ProblemDetailsToPB(prob)
if err != nil {
ra.log.AuditErrf("Could not convert order error problem to PB: %q", err)
return order
}
// Assign the protobuf problem to the field and save it via the SA
order.Error = pbProb
if err := ra.SA.SetOrderError(ctx, order); err != nil {
ra.log.AuditErrf("Could not persist order error: %q", err)
}
return order
}
// FinalizeOrder accepts a request to finalize an order object and, if possible,
// issues a certificate to satisfy the order. If an order does not have valid,
// unexpired authorizations for all of its associated names an error is
// returned. Similarly we vet that all of the names in the order are acceptable
// based on current policy and return an error if the order can't be fulfilled.
// If successful the order will be returned in processing status for the client
// to poll while awaiting finalization to occur.
func (ra *RegistrationAuthorityImpl) FinalizeOrder(ctx context.Context, req *rapb.FinalizeOrderRequest) (*corepb.Order, error) {
order := req.Order
if *order.Status != string(core.StatusReady) {
return nil, berrors.OrderNotReadyError(
"Order's status (%q) is not acceptable for finalization",
*order.Status)
}
// There should never be an order with 0 names at the stage the RA is
// processing the order but we check to be on the safe side, throwing an
// internal server error if this assumption is ever violated.
if len(order.Names) == 0 {
return nil, berrors.InternalServerError("Order has no associated names")
}
// Parse the CSR from the request
csrOb, err := x509.ParseCertificateRequest(req.Csr)
if err != nil {
return nil, err
}
if err := csrlib.VerifyCSR(csrOb, ra.maxNames, &ra.keyPolicy, ra.PA, ra.forceCNFromSAN, *req.Order.RegistrationID); err != nil {
return nil, berrors.MalformedError(err.Error())
}
// Dedupe, lowercase and sort both the names from the CSR and the names in the
// order.
csrNames := core.UniqueLowerNames(csrOb.DNSNames)
orderNames := core.UniqueLowerNames(order.Names)
// Immediately reject the request if the number of names differ
if len(orderNames) != len(csrNames) {
return nil, berrors.UnauthorizedError("Order includes different number of names than CSR specifies")
}
// Check that the order names and the CSR names are an exact match
for i, name := range orderNames {
if name != csrNames[i] {
return nil, berrors.UnauthorizedError("CSR is missing Order domain %q", name)
}
}
// Update the order to be status processing - we issue synchronously at the
// present time so this is somewhat artificial/unnecessary but allows planning
// for the future.
//
// NOTE(@cpu): After this point any errors that are encountered must update
// the state of the order to invalid by setting the order's error field.
// Otherwise the order will be "stuck" in processing state. It can not be
// finalized because it isn't pending, but we aren't going to process it
// further because we already did and encountered an error.
if err := ra.SA.SetOrderProcessing(ctx, order); err != nil {
// Fail the order with a server internal error - we weren't able to set the
// status to processing and that's unexpected & weird.
ra.failOrder(ctx, order, probs.ServerInternal("Error setting order processing"))
return nil, err
}
// Attempt issuance for the order. If the order isn't fully authorized this
// will return an error.
issueReq := core.CertificateRequest{
Bytes: req.Csr,
CSR: csrOb,
}
cert, err := ra.issueCertificate(ctx, issueReq, accountID(*order.RegistrationID), orderID(*order.Id))
if err != nil {
// Fail the order. The problem is computed using
// `web.ProblemDetailsForError`, the same function the WFE uses to convert
// between `berrors` and problems. This will turn normal expected berrors like
// berrors.UnauthorizedError into the correct
// `urn:ietf:params:acme:error:unauthorized` problem while not letting
// anything like a server internal error through with sensitive info.
ra.failOrder(ctx, order, web.ProblemDetailsForError(err, "Error finalizing order"))
return nil, err
}
// Parse the issued certificate to get the serial
parsedCertificate, err := x509.ParseCertificate([]byte(cert.DER))
if err != nil {
// Fail the order with a server internal error. The certificate we failed
// to parse was from our own CA. Bad news!
ra.failOrder(ctx, order, probs.ServerInternal("Error parsing certificate DER"))
return nil, err
}
serial := core.SerialToString(parsedCertificate.SerialNumber)
// Finalize the order with its new CertificateSerial
order.CertificateSerial = &serial
if err := ra.SA.FinalizeOrder(ctx, order); err != nil {
// Fail the order with a server internal error. We weren't able to persist
// the certificate serial and that's unexpected & weird.
ra.failOrder(ctx, order, probs.ServerInternal("Error persisting finalized order"))
return nil, err
}
// Update the order status locally since the SA doesn't return the updated
// order itself after setting the status
validStatus := string(core.StatusValid)
order.Status = &validStatus
return order, nil
}
// NewCertificate requests the issuance of a certificate.
func (ra *RegistrationAuthorityImpl) NewCertificate(ctx context.Context, req core.CertificateRequest, regID int64) (core.Certificate, error) {
// Verify the CSR
if err := csrlib.VerifyCSR(req.CSR, ra.maxNames, &ra.keyPolicy, ra.PA, ra.forceCNFromSAN, regID); err != nil {
return core.Certificate{}, berrors.MalformedError(err.Error())
}
// NewCertificate provides an order ID of 0, indicating this is a classic ACME
// v1 issuance request from the new certificate endpoint that is not
// associated with an ACME v2 order.
return ra.issueCertificate(ctx, req, accountID(regID), orderID(0))
}
// To help minimize the chance that an accountID would be used as an order ID
// (or vice versa) when calling `issueCertificate` we define internal
// `accountID` and `orderID` types so that callers must explicitly cast.
type accountID int64
type orderID int64
// issueCertificate sets up a log event structure and captures any errors
// encountered during issuance, then calls issueCertificateInner.
func (ra *RegistrationAuthorityImpl) issueCertificate(
ctx context.Context,
req core.CertificateRequest,
acctID accountID,
oID orderID) (core.Certificate, error) {
// Construct the log event
logEvent := certificateRequestEvent{
ID: core.NewToken(),
OrderID: int64(oID),
Requester: int64(acctID),
RequestTime: ra.clk.Now(),
}
var result string
cert, err := ra.issueCertificateInner(ctx, req, acctID, oID, &logEvent)
if err != nil {
logEvent.Error = err.Error()
result = "error"
} else {
result = "successful"
}
logEvent.ResponseTime = ra.clk.Now()
ra.log.AuditObject(fmt.Sprintf("Certificate request - %s", result), logEvent)
return cert, err
}
// issueCertificateInner handles the common aspects of certificate issuance used by
// both the "classic" NewCertificate endpoint (for ACME v1) and the