forked from adamlaska/boulder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsa.go
More file actions
2108 lines (1913 loc) · 66.1 KB
/
sa.go
File metadata and controls
2108 lines (1913 loc) · 66.1 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 sa
import (
"context"
"crypto/sha256"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"math/big"
"net"
"strings"
"sync"
"time"
"github.com/jmhodges/clock"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/ocsp"
"google.golang.org/protobuf/types/known/emptypb"
jose "gopkg.in/square/go-jose.v2"
"github.com/letsencrypt/boulder/core"
corepb "github.com/letsencrypt/boulder/core/proto"
"github.com/letsencrypt/boulder/db"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/features"
bgrpc "github.com/letsencrypt/boulder/grpc"
"github.com/letsencrypt/boulder/identifier"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/revocation"
rocsp_config "github.com/letsencrypt/boulder/rocsp/config"
sapb "github.com/letsencrypt/boulder/sa/proto"
)
var errIncompleteRequest = errors.New("incomplete gRPC request message")
type certCountFunc func(db db.Selector, domain string, timeRange *sapb.Range) (int64, error)
// SQLStorageAuthority defines a Storage Authority
type SQLStorageAuthority struct {
sapb.UnimplementedStorageAuthorityServer
dbMap *db.WrappedMap
dbReadOnlyMap *db.WrappedMap
// Redis client for storing OCSP responses in Redis.
rocspWriteClient rocspWriter
// Short issuer map used by rocsp.
shortIssuers []rocsp_config.ShortIDIssuer
clk clock.Clock
log blog.Logger
// For RPCs that generate multiple, parallelizable SQL queries, this is the
// max parallelism they will use (to avoid consuming too many MariaDB
// threads).
parallelismPerRPC int
// We use function types here so we can mock out this internal function in
// unittests.
countCertificatesByName certCountFunc
// rateLimitWriteErrors is a Counter for the number of times
// a ratelimit update transaction failed during AddCertificate request
// processing. We do not fail the overall AddCertificate call when ratelimit
// transactions fail and so use this stat to maintain visibility into the rate
// this occurs.
rateLimitWriteErrors prometheus.Counter
// redisStoreResponse is a counter of OCSP responses written to redis by
// result.
redisStoreResponse *prometheus.CounterVec
}
// orderFQDNSet contains the SHA256 hash of the lowercased, comma joined names
// from a new-order request, along with the corresponding orderID, the
// registration ID, and the order expiry. This is used to find
// existing orders for reuse.
type orderFQDNSet struct {
ID int64
SetHash []byte
OrderID int64
RegistrationID int64
Expires time.Time
}
// NewSQLStorageAuthority provides persistence using a SQL backend for
// Boulder. It will modify the given gorp.DbMap by adding relevant tables.
func NewSQLStorageAuthority(
dbMap *db.WrappedMap,
dbReadOnlyMap *db.WrappedMap,
rocspWriteClient rocspWriter,
shortIssuers []rocsp_config.ShortIDIssuer,
clk clock.Clock,
logger blog.Logger,
stats prometheus.Registerer,
parallelismPerRPC int,
) (*SQLStorageAuthority, error) {
SetSQLDebug(dbMap, logger)
rateLimitWriteErrors := prometheus.NewCounter(prometheus.CounterOpts{
Name: "rate_limit_write_errors",
Help: "number of failed ratelimit update transactions during AddCertificate",
})
stats.MustRegister(rateLimitWriteErrors)
redisStoreResponse := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "redis_store_response",
Help: "Count of OCSP Response writes to redis",
}, []string{"result"})
stats.MustRegister(redisStoreResponse)
ssa := &SQLStorageAuthority{
dbMap: dbMap,
dbReadOnlyMap: dbReadOnlyMap,
rocspWriteClient: rocspWriteClient,
shortIssuers: shortIssuers,
clk: clk,
log: logger,
parallelismPerRPC: parallelismPerRPC,
rateLimitWriteErrors: rateLimitWriteErrors,
redisStoreResponse: redisStoreResponse,
}
ssa.countCertificatesByName = ssa.countCertificates
return ssa, nil
}
// GetRegistration obtains a Registration by ID
func (ssa *SQLStorageAuthority) GetRegistration(ctx context.Context, req *sapb.RegistrationID) (*corepb.Registration, error) {
if req == nil || req.Id == 0 {
return nil, errIncompleteRequest
}
const query = "WHERE id = ?"
model, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, req.Id)
if err != nil {
if db.IsNoRows(err) {
return nil, berrors.NotFoundError("registration with ID '%d' not found", req.Id)
}
return nil, err
}
return registrationModelToPb(model)
}
// GetRegistrationByKey obtains a Registration by JWK
func (ssa *SQLStorageAuthority) GetRegistrationByKey(ctx context.Context, req *sapb.JSONWebKey) (*corepb.Registration, error) {
if req == nil || len(req.Jwk) == 0 {
return nil, errIncompleteRequest
}
var jwk jose.JSONWebKey
err := jwk.UnmarshalJSON(req.Jwk)
if err != nil {
return nil, err
}
const query = "WHERE jwk_sha256 = ?"
sha, err := core.KeyDigestB64(jwk.Key)
if err != nil {
return nil, err
}
model, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, sha)
if err != nil {
if db.IsNoRows(err) {
return nil, berrors.NotFoundError("no registrations with public key sha256 %q", sha)
}
return nil, err
}
return registrationModelToPb(model)
}
// incrementIP returns a copy of `ip` incremented at a bit index `index`,
// or in other words the first IP of the next highest subnet given a mask of
// length `index`.
// In order to easily account for overflow, we treat ip as a big.Int and add to
// it. If the increment overflows the max size of a net.IP, return the highest
// possible net.IP.
func incrementIP(ip net.IP, index int) net.IP {
bigInt := new(big.Int)
bigInt.SetBytes([]byte(ip))
incr := new(big.Int).Lsh(big.NewInt(1), 128-uint(index))
bigInt.Add(bigInt, incr)
// bigInt.Bytes can be shorter than 16 bytes, so stick it into a
// full-sized net.IP.
resultBytes := bigInt.Bytes()
if len(resultBytes) > 16 {
return net.ParseIP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
}
result := make(net.IP, 16)
copy(result[16-len(resultBytes):], resultBytes)
return result
}
// ipRange returns a range of IP addresses suitable for querying MySQL for the
// purpose of rate limiting using a range that is inclusive on the lower end and
// exclusive at the higher end. If ip is an IPv4 address, it returns that address,
// plus the one immediately higher than it. If ip is an IPv6 address, it applies
// a /48 mask to it and returns the lowest IP in the resulting network, and the
// first IP outside of the resulting network.
func ipRange(ip net.IP) (net.IP, net.IP) {
ip = ip.To16()
// For IPv6, match on a certain subnet range, since one person can commonly
// have an entire /48 to themselves.
maskLength := 48
// For IPv4 addresses, do a match on exact address, so begin = ip and end =
// next higher IP.
if ip.To4() != nil {
maskLength = 128
}
mask := net.CIDRMask(maskLength, 128)
begin := ip.Mask(mask)
end := incrementIP(begin, maskLength)
return begin, end
}
// CountRegistrationsByIP returns the number of registrations created in the
// time range for a single IP address.
func (ssa *SQLStorageAuthority) CountRegistrationsByIP(ctx context.Context, req *sapb.CountRegistrationsByIPRequest) (*sapb.Count, error) {
if len(req.Ip) == 0 || req.Range.Earliest == 0 || req.Range.Latest == 0 {
return nil, errIncompleteRequest
}
var count int64
err := ssa.dbReadOnlyMap.WithContext(ctx).SelectOne(
&count,
`SELECT COUNT(1) FROM registrations
WHERE
initialIP = :ip AND
:earliest < createdAt AND
createdAt <= :latest`,
map[string]interface{}{
"ip": req.Ip,
"earliest": time.Unix(0, req.Range.Earliest),
"latest": time.Unix(0, req.Range.Latest),
})
if err != nil {
return &sapb.Count{Count: -1}, err
}
return &sapb.Count{Count: count}, nil
}
// CountRegistrationsByIPRange returns the number of registrations created in
// the time range in an IP range. For IPv4 addresses, that range is limited to
// the single IP. For IPv6 addresses, that range is a /48, since it's not
// uncommon for one person to have a /48 to themselves.
func (ssa *SQLStorageAuthority) CountRegistrationsByIPRange(ctx context.Context, req *sapb.CountRegistrationsByIPRequest) (*sapb.Count, error) {
if len(req.Ip) == 0 || req.Range.Earliest == 0 || req.Range.Latest == 0 {
return nil, errIncompleteRequest
}
var count int64
beginIP, endIP := ipRange(req.Ip)
err := ssa.dbReadOnlyMap.WithContext(ctx).SelectOne(
&count,
`SELECT COUNT(1) FROM registrations
WHERE
:beginIP <= initialIP AND
initialIP < :endIP AND
:earliest < createdAt AND
createdAt <= :latest`,
map[string]interface{}{
"earliest": time.Unix(0, req.Range.Earliest),
"latest": time.Unix(0, req.Range.Latest),
"beginIP": beginIP,
"endIP": endIP,
})
if err != nil {
return &sapb.Count{Count: -1}, err
}
return &sapb.Count{Count: count}, nil
}
// CountCertificatesByNames counts, for each input domain, the number of
// certificates issued in the given time range for that domain and its
// subdomains. It returns a map from domains to counts, which is guaranteed to
// contain an entry for each input domain, so long as err is nil.
// Queries will be run in parallel. If any of them error, only one error will
// be returned.
func (ssa *SQLStorageAuthority) CountCertificatesByNames(ctx context.Context, req *sapb.CountCertificatesByNamesRequest) (*sapb.CountByNames, error) {
if len(req.Names) == 0 || req.Range.Earliest == 0 || req.Range.Latest == 0 {
return nil, errIncompleteRequest
}
work := make(chan string, len(req.Names))
type result struct {
err error
count int64
domain string
}
results := make(chan result, len(req.Names))
for _, domain := range req.Names {
work <- domain
}
close(work)
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// We may perform up to 100 queries, depending on what's in the certificate
// request. Parallelize them so we don't hit our timeout, but limit the
// parallelism so we don't consume too many threads on the database.
for i := 0; i < ssa.parallelismPerRPC; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for domain := range work {
select {
case <-ctx.Done():
results <- result{err: ctx.Err()}
return
default:
}
currentCount, err := ssa.countCertificatesByName(ssa.dbReadOnlyMap.WithContext(ctx), domain, req.Range)
if err != nil {
results <- result{err: err}
// Skip any further work
cancel()
return
}
results <- result{
count: currentCount,
domain: domain,
}
}
}()
}
wg.Wait()
close(results)
counts := make(map[string]int64)
for r := range results {
if r.err != nil {
return nil, r.err
}
counts[r.domain] = r.count
}
return &sapb.CountByNames{Counts: counts}, nil
}
func ReverseName(domain string) string {
labels := strings.Split(domain, ".")
for i, j := 0, len(labels)-1; i < j; i, j = i+1, j-1 {
labels[i], labels[j] = labels[j], labels[i]
}
return strings.Join(labels, ".")
}
// GetCertificate takes a serial number and returns the corresponding
// certificate, or error if it does not exist.
func (ssa *SQLStorageAuthority) GetCertificate(ctx context.Context, req *sapb.Serial) (*corepb.Certificate, error) {
if req == nil || req.Serial == "" {
return nil, errIncompleteRequest
}
if !core.ValidSerial(req.Serial) {
return nil, fmt.Errorf("Invalid certificate serial %s", req.Serial)
}
cert, err := SelectCertificate(ssa.dbMap.WithContext(ctx), req.Serial)
if db.IsNoRows(err) {
return nil, berrors.NotFoundError("certificate with serial %q not found", req.Serial)
}
if err != nil {
return nil, err
}
return bgrpc.CertToPB(cert), nil
}
// GetCertificateStatus takes a hexadecimal string representing the full 128-bit serial
// number of a certificate and returns data about that certificate's current
// validity.
func (ssa *SQLStorageAuthority) GetCertificateStatus(ctx context.Context, req *sapb.Serial) (*corepb.CertificateStatus, error) {
if req.Serial == "" {
return nil, errIncompleteRequest
}
if !core.ValidSerial(req.Serial) {
err := fmt.Errorf("Invalid certificate serial %s", req.Serial)
return nil, err
}
certStatus, err := SelectCertificateStatus(ssa.dbMap.WithContext(ctx), req.Serial)
if err != nil {
return nil, err
}
return bgrpc.CertStatusToPB(certStatus), nil
}
// NewRegistration stores a new Registration
func (ssa *SQLStorageAuthority) NewRegistration(ctx context.Context, req *corepb.Registration) (*corepb.Registration, error) {
if len(req.Key) == 0 || len(req.InitialIP) == 0 {
return nil, errIncompleteRequest
}
reg, err := registrationPbToModel(req)
if err != nil {
return nil, err
}
reg.CreatedAt = ssa.clk.Now()
err = ssa.dbMap.WithContext(ctx).Insert(reg)
if err != nil {
if db.IsDuplicate(err) {
// duplicate entry error can only happen when jwk_sha256 collides, indicate
// to caller that the provided key is already in use
return nil, berrors.DuplicateError("key is already in use for a different account")
}
return nil, err
}
return registrationModelToPb(reg)
}
// UpdateRegistration stores an updated Registration
func (ssa *SQLStorageAuthority) UpdateRegistration(ctx context.Context, req *corepb.Registration) (*emptypb.Empty, error) {
if req == nil || req.Id == 0 || len(req.Key) == 0 || len(req.InitialIP) == 0 {
return nil, errIncompleteRequest
}
const query = "WHERE id = ?"
curr, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, req.Id)
if err != nil {
if db.IsNoRows(err) {
return nil, berrors.NotFoundError("registration with ID '%d' not found", req.Id)
}
return nil, err
}
update, err := registrationPbToModel(req)
if err != nil {
return nil, err
}
// Copy the existing registration model's LockCol to the new updated
// registration model's LockCol
update.LockCol = curr.LockCol
n, err := ssa.dbMap.WithContext(ctx).Update(update)
if err != nil {
if db.IsDuplicate(err) {
// duplicate entry error can only happen when jwk_sha256 collides, indicate
// to caller that the provided key is already in use
return nil, berrors.DuplicateError("key is already in use for a different account")
}
return nil, err
}
if n == 0 {
return nil, berrors.NotFoundError("registration with ID '%d' not found", req.Id)
}
return &emptypb.Empty{}, nil
}
// AddCertificate stores an issued certificate and returns the digest as
// a string, or an error if any occurred.
func (ssa *SQLStorageAuthority) AddCertificate(ctx context.Context, req *sapb.AddCertificateRequest) (*sapb.AddCertificateResponse, error) {
if len(req.Der) == 0 || req.RegID == 0 || req.Issued == 0 {
return nil, errIncompleteRequest
}
parsedCertificate, err := x509.ParseCertificate(req.Der)
if err != nil {
return nil, err
}
digest := core.Fingerprint256(req.Der)
serial := core.SerialToString(parsedCertificate.SerialNumber)
cert := &core.Certificate{
RegistrationID: req.RegID,
Serial: serial,
Digest: digest,
DER: req.Der,
Issued: time.Unix(0, req.Issued),
Expires: parsedCertificate.NotAfter,
}
isRenewalRaw, overallError := db.WithTransaction(ctx, ssa.dbMap, func(txWithCtx db.Executor) (interface{}, error) {
// Select to see if cert exists
var row struct {
Count int64
}
err := txWithCtx.SelectOne(&row, "SELECT count(1) as count FROM certificates WHERE serial=?", serial)
if err != nil {
return nil, err
}
if row.Count > 0 {
return nil, berrors.DuplicateError("cannot add a duplicate cert")
}
// Save the final certificate
err = txWithCtx.Insert(cert)
if err != nil {
return nil, err
}
// NOTE(@cpu): When we collect up names to check if an FQDN set exists (e.g.
// that it is a renewal) we use just the DNSNames from the certificate and
// ignore the Subject Common Name (if any). This is a safe assumption because
// if a certificate we issued were to have a Subj. CN not present as a SAN it
// would be a misissuance and miscalculating whether the cert is a renewal or
// not for the purpose of rate limiting is the least of our troubles.
isRenewal, err := ssa.checkFQDNSetExists(
txWithCtx.SelectOne,
parsedCertificate.DNSNames)
if err != nil {
return nil, err
}
return isRenewal, err
})
if overallError != nil {
return nil, overallError
}
// Recast the interface{} return from db.WithTransaction as a bool, returning
// an error if we can't.
var isRenewal bool
if boolVal, ok := isRenewalRaw.(bool); !ok {
return nil, fmt.Errorf(
"AddCertificate db.WithTransaction returned %T out var, expected bool",
isRenewalRaw)
} else {
isRenewal = boolVal
}
// In a separate transaction perform the work required to update tables used
// for rate limits. Since the effects of failing these writes is slight
// miscalculation of rate limits we choose to not fail the AddCertificate
// operation if the rate limit update transaction fails.
_, rlTransactionErr := db.WithTransaction(ctx, ssa.dbMap, func(txWithCtx db.Executor) (interface{}, error) {
// Add to the rate limit table, but only for new certificates. Renewals
// don't count against the certificatesPerName limit.
if !isRenewal {
timeToTheHour := parsedCertificate.NotBefore.Round(time.Hour)
err := ssa.addCertificatesPerName(ctx, txWithCtx, parsedCertificate.DNSNames, timeToTheHour)
if err != nil {
return nil, err
}
}
// Update the FQDN sets now that there is a final certificate to ensure rate
// limits are calculated correctly.
err = addFQDNSet(
txWithCtx,
parsedCertificate.DNSNames,
core.SerialToString(parsedCertificate.SerialNumber),
parsedCertificate.NotBefore,
parsedCertificate.NotAfter,
)
if err != nil {
return nil, err
}
return nil, nil
})
// If the ratelimit transaction failed increment a stat and log a warning
// but don't return an error from AddCertificate.
if rlTransactionErr != nil {
ssa.rateLimitWriteErrors.Inc()
ssa.log.AuditErrf("failed AddCertificate ratelimit update transaction: %v", rlTransactionErr)
}
return &sapb.AddCertificateResponse{Digest: digest}, nil
}
func (ssa *SQLStorageAuthority) CountOrders(ctx context.Context, req *sapb.CountOrdersRequest) (*sapb.Count, error) {
if req.AccountID == 0 || req.Range.Earliest == 0 || req.Range.Latest == 0 {
return nil, errIncompleteRequest
}
if features.Enabled(features.FasterNewOrdersRateLimit) {
return countNewOrders(ctx, ssa.dbReadOnlyMap, req)
}
var count int64
err := ssa.dbReadOnlyMap.WithContext(ctx).SelectOne(
&count,
`SELECT count(1) FROM orders
WHERE registrationID = :acctID AND
created >= :earliest AND
created < :latest`,
map[string]interface{}{
"acctID": req.AccountID,
"earliest": time.Unix(0, req.Range.Earliest),
"latest": time.Unix(0, req.Range.Latest),
},
)
if err != nil {
return nil, err
}
return &sapb.Count{Count: count}, nil
}
// HashNames returns a hash of the names requested. This is intended for use
// when interacting with the orderFqdnSets table.
func HashNames(names []string) []byte {
names = core.UniqueLowerNames(names)
hash := sha256.Sum256([]byte(strings.Join(names, ",")))
return hash[:]
}
func addFQDNSet(db db.Inserter, names []string, serial string, issued time.Time, expires time.Time) error {
return db.Insert(&core.FQDNSet{
SetHash: HashNames(names),
Serial: serial,
Issued: issued,
Expires: expires,
})
}
// addOrderFQDNSet creates a new OrderFQDNSet row using the provided
// information. This function accepts a transaction so that the orderFqdnSet
// addition can take place within the order addition transaction. The caller is
// required to rollback the transaction if an error is returned.
func addOrderFQDNSet(
db db.Inserter,
names []string,
orderID int64,
regID int64,
expires time.Time) error {
return db.Insert(&orderFQDNSet{
SetHash: HashNames(names),
OrderID: orderID,
RegistrationID: regID,
Expires: expires,
})
}
// deleteOrderFQDNSet deletes a OrderFQDNSet row that matches the provided
// orderID. This function accepts a transaction so that the deletion can
// take place within the finalization transaction. The caller is required to
// rollback the transaction if an error is returned.
func deleteOrderFQDNSet(
db db.Execer,
orderID int64) error {
result, err := db.Exec(`
DELETE FROM orderFqdnSets
WHERE orderID = ?`,
orderID)
if err != nil {
return err
}
rowsDeleted, err := result.RowsAffected()
if err != nil {
return err
}
// We always expect there to be an order FQDN set row for each
// pending/processing order that is being finalized. If there isn't one then
// something is amiss and should be raised as an internal server error
if rowsDeleted == 0 {
return berrors.InternalServerError("No orderFQDNSet exists to delete")
}
return nil
}
func addIssuedNames(db db.Execer, cert *x509.Certificate, isRenewal bool) error {
if len(cert.DNSNames) == 0 {
return berrors.InternalServerError("certificate has no DNSNames")
}
var qmarks []string
var values []interface{}
for _, name := range cert.DNSNames {
values = append(values,
ReverseName(name),
core.SerialToString(cert.SerialNumber),
cert.NotBefore,
isRenewal)
qmarks = append(qmarks, "(?, ?, ?, ?)")
}
query := `INSERT INTO issuedNames (reversedName, serial, notBefore, renewal) VALUES ` + strings.Join(qmarks, ", ") + `;`
_, err := db.Exec(query, values...)
return err
}
// CountFQDNSets counts the total number of issuances, for a set of domains,
// that occurred during a given window of time.
func (ssa *SQLStorageAuthority) CountFQDNSets(ctx context.Context, req *sapb.CountFQDNSetsRequest) (*sapb.Count, error) {
if req.Window == 0 || len(req.Domains) == 0 {
return nil, errIncompleteRequest
}
var count int64
err := ssa.dbReadOnlyMap.WithContext(ctx).SelectOne(
&count,
// We don't do a select across both fqdnSets and fqdnSets_old here because
// this method is only used for rate-limiting and we don't care to spend the
// extra CPU cycles checking the old table.
// TODO(#5670): Remove this comment when the partitioning is fixed.
`SELECT COUNT(1) FROM fqdnSets
WHERE setHash = ?
AND issued > ?`,
HashNames(req.Domains),
ssa.clk.Now().Add(-time.Duration(req.Window)),
)
return &sapb.Count{Count: count}, err
}
// FQDNSetExists returns a bool indicating if one or more FQDN sets |names|
// exists in the database
func (ssa *SQLStorageAuthority) FQDNSetExists(ctx context.Context, req *sapb.FQDNSetExistsRequest) (*sapb.Exists, error) {
if len(req.Domains) == 0 {
return nil, errIncompleteRequest
}
exists, err := ssa.checkFQDNSetExists(ssa.dbMap.WithContext(ctx).SelectOne, req.Domains)
if err != nil {
return nil, err
}
return &sapb.Exists{Exists: exists}, nil
}
// oneSelectorFunc is a func type that matches both gorp.Transaction.SelectOne
// and gorp.DbMap.SelectOne.
type oneSelectorFunc func(holder interface{}, query string, args ...interface{}) error
// checkFQDNSetExists uses the given oneSelectorFunc to check whether an fqdnSet
// for the given names exists.
func (ssa *SQLStorageAuthority) checkFQDNSetExists(selector oneSelectorFunc, names []string) (bool, error) {
namehash := HashNames(names)
var exists bool
err := selector(
&exists,
// We select on both tables here because this function is used to determine
// if a given issuance is a renewal, and for that we care about 90 days
// worth of data, not just 7 days like the current fqdnSets table holds.
// TODO(#5670): Remove this OR when the partitioning is fixed.
`SELECT EXISTS (SELECT id FROM fqdnSets WHERE setHash = ? LIMIT 1)
OR EXISTS (SELECT id FROM fqdnSets_old WHERE setHash = ? LIMIT 1)`,
namehash,
namehash,
)
return exists, err
}
// PreviousCertificateExists returns true iff there was at least one certificate
// issued with the provided domain name, and the most recent such certificate
// was issued by the provided registration ID. This method is currently only
// used to determine if a certificate has previously been issued for a given
// domain name in order to determine if validations should be allowed during
// the v1 API shutoff.
// TODO(#5816): Consider removing this method, as it has no callers.
func (ssa *SQLStorageAuthority) PreviousCertificateExists(ctx context.Context, req *sapb.PreviousCertificateExistsRequest) (*sapb.Exists, error) {
if req.Domain == "" || req.RegID == 0 {
return nil, errIncompleteRequest
}
exists := &sapb.Exists{Exists: true}
notExists := &sapb.Exists{Exists: false}
// Find the most recently issued certificate containing this domain name.
var serial string
err := ssa.dbMap.WithContext(ctx).SelectOne(
&serial,
`SELECT serial FROM issuedNames
WHERE reversedName = ?
ORDER BY notBefore DESC
LIMIT 1`,
ReverseName(req.Domain),
)
if err != nil {
if db.IsNoRows(err) {
return notExists, nil
}
return nil, err
}
// Check whether that certificate was issued to the specified account.
var count int
err = ssa.dbMap.WithContext(ctx).SelectOne(
&count,
`SELECT COUNT(1) FROM certificates
WHERE serial = ?
AND registrationID = ?`,
serial,
req.RegID,
)
if err != nil {
// If no rows found, that means the certificate we found in issuedNames wasn't
// issued by the registration ID we are checking right now, but is not an
// error.
if db.IsNoRows(err) {
return notExists, nil
}
return nil, err
}
if count > 0 {
return exists, nil
}
return notExists, nil
}
// DeactivateRegistration deactivates a currently valid registration
func (ssa *SQLStorageAuthority) DeactivateRegistration(ctx context.Context, req *sapb.RegistrationID) (*emptypb.Empty, error) {
if req == nil || req.Id == 0 {
return nil, errIncompleteRequest
}
_, err := ssa.dbMap.WithContext(ctx).Exec(
"UPDATE registrations SET status = ? WHERE status = ? AND id = ?",
string(core.StatusDeactivated),
string(core.StatusValid),
req.Id,
)
if err != nil {
return nil, err
}
return &emptypb.Empty{}, nil
}
// DeactivateAuthorization2 deactivates a currently valid or pending authorization.
// This method is intended to deprecate DeactivateAuthorization.
func (ssa *SQLStorageAuthority) DeactivateAuthorization2(ctx context.Context, req *sapb.AuthorizationID2) (*emptypb.Empty, error) {
if req.Id == 0 {
return nil, errIncompleteRequest
}
_, err := ssa.dbMap.Exec(
`UPDATE authz2 SET status = :deactivated WHERE id = :id and status IN (:valid,:pending)`,
map[string]interface{}{
"deactivated": statusUint(core.StatusDeactivated),
"id": req.Id,
"valid": statusUint(core.StatusValid),
"pending": statusUint(core.StatusPending),
},
)
if err != nil {
return nil, err
}
return &emptypb.Empty{}, nil
}
// NewOrder adds a new v2 style order to the database
func (ssa *SQLStorageAuthority) NewOrder(ctx context.Context, req *sapb.NewOrderRequest) (*corepb.Order, error) {
output, err := db.WithTransaction(ctx, ssa.dbMap, func(txWithCtx db.Executor) (interface{}, error) {
// Check new order request fields.
if req.RegistrationID == 0 || req.Expires == 0 || len(req.Names) == 0 {
return nil, errIncompleteRequest
}
order := &orderModel{
RegistrationID: req.RegistrationID,
Expires: time.Unix(0, req.Expires),
Created: ssa.clk.Now(),
}
err := txWithCtx.Insert(order)
if err != nil {
return nil, err
}
for _, id := range req.V2Authorizations {
otoa := &orderToAuthzModel{
OrderID: order.ID,
AuthzID: id,
}
err := txWithCtx.Insert(otoa)
if err != nil {
return nil, err
}
}
for _, name := range req.Names {
reqdName := &requestedNameModel{
OrderID: order.ID,
ReversedName: ReverseName(name),
}
err := txWithCtx.Insert(reqdName)
if err != nil {
return nil, err
}
}
// Add an FQDNSet entry for the order
err = addOrderFQDNSet(txWithCtx, req.Names, order.ID, order.RegistrationID, order.Expires)
if err != nil {
return nil, err
}
return order, nil
})
if err != nil {
return nil, err
}
var order *orderModel
var ok bool
if order, ok = output.(*orderModel); !ok {
return nil, fmt.Errorf("shouldn't happen: casting error in NewOrder")
}
if features.Enabled(features.FasterNewOrdersRateLimit) {
// Increment the order creation count
err := addNewOrdersRateLimit(ctx, ssa.dbMap, req.RegistrationID, ssa.clk.Now().Truncate(time.Minute))
if err != nil {
return nil, err
}
}
res := &corepb.Order{
// Carry some fields over the from input new order request.
RegistrationID: req.RegistrationID,
Expires: req.Expires,
Names: req.Names,
V2Authorizations: req.V2Authorizations,
// Some fields were generated by the database transaction.
Id: order.ID,
Created: order.Created.UnixNano(),
// A new order is never processing because it can't have been finalized yet.
BeganProcessing: false,
}
// Calculate the order status before returning it. Since it may have reused all
// valid authorizations the order may be "born" in a ready status.
status, err := ssa.statusForOrder(ctx, res)
if err != nil {
return nil, err
}
res.Status = status
return res, nil
}
// NewOrderAndAuthzs adds the given authorizations to the database, adds their
// autogenerated IDs to the given order, and then adds the order to the db.
// This is done inside a single transaction to prevent situations where new
// authorizations are created, but then their corresponding order is never
// created, leading to "invisible" pending authorizations.
func (ssa *SQLStorageAuthority) NewOrderAndAuthzs(ctx context.Context, req *sapb.NewOrderAndAuthzsRequest) (*corepb.Order, error) {
output, err := db.WithTransaction(ctx, ssa.dbMap, func(txWithCtx db.Executor) (interface{}, error) {
// First, insert all of the new authorizations and record their IDs.
newAuthzIDs := make([]int64, 0)
if len(req.NewAuthzs) != 0 {
inserter, err := db.NewMultiInserter("authz2", authzFields, "id")
if err != nil {
return nil, err
}
for _, authz := range req.NewAuthzs {
if authz.Status != string(core.StatusPending) {
return nil, berrors.InternalServerError("authorization must be pending")
}
am, err := authzPBToModel(authz)
if err != nil {
return nil, err
}
err = inserter.Add([]interface{}{
am.ID,
am.IdentifierType,
am.IdentifierValue,
am.RegistrationID,
am.Status,
am.Expires,
am.Challenges,
am.Attempted,
am.AttemptedAt,
am.Token,
am.ValidationError,
am.ValidationRecord,
})
if err != nil {
return nil, err
}
}
newAuthzIDs, err = inserter.Insert(txWithCtx)
if err != nil {
return nil, err
}
}
// Second, insert the new order.
order := &orderModel{
RegistrationID: req.NewOrder.RegistrationID,
Expires: time.Unix(0, req.NewOrder.Expires),
Created: ssa.clk.Now(),
}
err := txWithCtx.Insert(order)
if err != nil {
return nil, err
}
// Third, insert all of the orderToAuthz relations.
inserter, err := db.NewMultiInserter("orderToAuthz2", "orderID, authzID", "")
if err != nil {
return nil, err
}
for _, id := range req.NewOrder.V2Authorizations {
err = inserter.Add([]interface{}{order.ID, id})
if err != nil {
return nil, err
}
}
for _, id := range newAuthzIDs {
err = inserter.Add([]interface{}{order.ID, id})
if err != nil {
return nil, err
}
}
_, err = inserter.Insert(txWithCtx)
if err != nil {
return nil, err
}