-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathsa.go
1803 lines (1652 loc) · 58.1 KB
/
sa.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 sa
import (
"context"
"crypto/sha256"
"crypto/x509"
"encoding/json"
"fmt"
"math/big"
"net"
"strings"
"sync"
"time"
"github.com/jmhodges/clock"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/go-gorp/gorp.v2"
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"
bgrpc "github.com/letsencrypt/boulder/grpc"
"github.com/letsencrypt/boulder/identifier"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/revocation"
sapb "github.com/letsencrypt/boulder/sa/proto"
)
type certCountFunc func(db db.Selector, domain string, earliest, latest time.Time) (int, error)
// SQLStorageAuthority defines a Storage Authority
type SQLStorageAuthority struct {
dbMap *db.WrappedMap
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
}
func digest256(data []byte) []byte {
d := sha256.New()
_, _ = d.Write(data) // Never returns an error
return d.Sum(nil)
}
// 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
}
const (
authorizationTable = "authz"
pendingAuthorizationTable = "pendingAuthorizations"
)
var authorizationTables = []string{
authorizationTable,
pendingAuthorizationTable,
}
// 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,
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)
ssa := &SQLStorageAuthority{
dbMap: dbMap,
clk: clk,
log: logger,
parallelismPerRPC: parallelismPerRPC,
rateLimitWriteErrors: rateLimitWriteErrors,
}
ssa.countCertificatesByName = ssa.countCertificates
return ssa, nil
}
func statusIsPending(status core.AcmeStatus) bool {
return status == core.StatusPending || status == core.StatusProcessing || status == core.StatusUnknown
}
func existingPending(dbMap db.OneSelector, id string) bool {
var count int64
_ = dbMap.SelectOne(&count, "SELECT count(*) FROM pendingAuthorizations WHERE id = :id", map[string]interface{}{"id": id})
return count > 0
}
func existingFinal(dbMap db.OneSelector, id string) bool {
var count int64
_ = dbMap.SelectOne(&count, "SELECT count(*) FROM authz WHERE id = :id", map[string]interface{}{"id": id})
return count > 0
}
func existingRegistration(tx *gorp.Transaction, id int64) bool {
var count int64
_ = tx.SelectOne(&count, "SELECT count(*) FROM registrations WHERE id = :id", map[string]interface{}{"id": id})
return count > 0
}
// GetRegistration obtains a Registration by ID
func (ssa *SQLStorageAuthority) GetRegistration(ctx context.Context, id int64) (core.Registration, error) {
const query = "WHERE id = ?"
model, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, id)
if err != nil {
if db.IsNoRows(err) {
return core.Registration{}, berrors.NotFoundError("registration with ID '%d' not found", id)
}
return core.Registration{}, err
}
return modelToRegistration(model)
}
// GetRegistrationByKey obtains a Registration by JWK
func (ssa *SQLStorageAuthority) GetRegistrationByKey(ctx context.Context, key *jose.JSONWebKey) (core.Registration, error) {
const query = "WHERE jwk_sha256 = ?"
if key == nil {
return core.Registration{}, fmt.Errorf("key argument to GetRegistrationByKey must not be nil")
}
sha, err := core.KeyDigest(key.Key)
if err != nil {
return core.Registration{}, err
}
model, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, sha)
if db.IsNoRows(err) {
return core.Registration{}, berrors.NotFoundError("no registrations with public key sha256 %q", sha)
}
if err != nil {
return core.Registration{}, err
}
return modelToRegistration(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, ip net.IP, earliest time.Time, latest time.Time) (int, error) {
var count int64
err := ssa.dbMap.WithContext(ctx).SelectOne(
&count,
`SELECT COUNT(1) FROM registrations
WHERE
initialIP = :ip AND
:earliest < createdAt AND
createdAt <= :latest`,
map[string]interface{}{
"ip": []byte(ip),
"earliest": earliest,
"latest": latest,
})
if err != nil {
return -1, err
}
return int(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, ip net.IP, earliest time.Time, latest time.Time) (int, error) {
var count int64
beginIP, endIP := ipRange(ip)
err := ssa.dbMap.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": earliest,
"latest": latest,
"beginIP": []byte(beginIP),
"endIP": []byte(endIP),
})
if err != nil {
return -1, err
}
return int(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, domains []string, earliest, latest time.Time) ([]*sapb.CountByNames_MapElement, error) {
work := make(chan string, len(domains))
type result struct {
err error
count int
domain string
}
results := make(chan result, len(domains))
for _, domain := range domains {
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.dbMap.WithContext(ctx), domain, earliest, latest)
if err != nil {
results <- result{err: err}
// Skip any further work
cancel()
return
}
results <- result{
count: currentCount,
domain: domain,
}
}
}()
}
wg.Wait()
close(results)
var ret []*sapb.CountByNames_MapElement
for r := range results {
if r.err != nil {
return nil, r.err
}
name := string(r.domain)
pbCount := int64(r.count)
ret = append(ret, &sapb.CountByNames_MapElement{
Name: &name,
Count: &pbCount,
})
}
return ret, 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, serial string) (core.Certificate, error) {
if !core.ValidSerial(serial) {
err := fmt.Errorf("Invalid certificate serial %s", serial)
return core.Certificate{}, err
}
cert, err := SelectCertificate(ssa.dbMap.WithContext(ctx), "WHERE serial = ?", serial)
if db.IsNoRows(err) {
return core.Certificate{}, berrors.NotFoundError("certificate with serial %q not found", serial)
}
if err != nil {
return core.Certificate{}, err
}
return cert, err
}
// 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, serial string) (core.CertificateStatus, error) {
if !core.ValidSerial(serial) {
err := fmt.Errorf("Invalid certificate serial %s", serial)
return core.CertificateStatus{}, err
}
statusModel, err := SelectCertificateStatus(
ssa.dbMap.WithContext(ctx),
"WHERE serial = ?",
serial,
)
if err != nil {
return core.CertificateStatus{}, err
}
return core.CertificateStatus{
Serial: statusModel.Serial,
Status: statusModel.Status,
OCSPLastUpdated: statusModel.OCSPLastUpdated,
RevokedDate: statusModel.RevokedDate,
RevokedReason: statusModel.RevokedReason,
LastExpirationNagSent: statusModel.LastExpirationNagSent,
OCSPResponse: statusModel.OCSPResponse,
NotAfter: statusModel.NotAfter,
IsExpired: statusModel.IsExpired,
}, nil
}
// NewRegistration stores a new Registration
func (ssa *SQLStorageAuthority) NewRegistration(ctx context.Context, reg core.Registration) (core.Registration, error) {
reg.CreatedAt = ssa.clk.Now()
rm, err := registrationToModel(®)
if err != nil {
return reg, err
}
err = ssa.dbMap.WithContext(ctx).Insert(rm)
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 reg, berrors.DuplicateError("key is already in use for a different account")
}
return reg, err
}
return modelToRegistration(rm)
}
// UpdateRegistration stores an updated Registration
func (ssa *SQLStorageAuthority) UpdateRegistration(ctx context.Context, reg core.Registration) error {
const query = "WHERE id = ?"
model, err := selectRegistration(ssa.dbMap.WithContext(ctx), query, reg.ID)
if err != nil {
if db.IsNoRows(err) {
return berrors.NotFoundError("registration with ID '%d' not found", reg.ID)
}
return err
}
updatedRegModel, err := registrationToModel(®)
if err != nil {
return err
}
// Copy the existing registration model's LockCol to the new updated
// registration model's LockCol
updatedRegModel.LockCol = model.LockCol
n, err := ssa.dbMap.WithContext(ctx).Update(updatedRegModel)
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 berrors.DuplicateError("key is already in use for a different account")
}
return err
}
if n == 0 {
return berrors.NotFoundError("registration with ID '%d' not found", reg.ID)
}
return 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,
certDER []byte,
regID int64,
ocspResponse []byte,
issued *time.Time) (string, error) {
parsedCertificate, err := x509.ParseCertificate(certDER)
if err != nil {
return "", err
}
digest := core.Fingerprint256(certDER)
serial := core.SerialToString(parsedCertificate.SerialNumber)
cert := &core.Certificate{
RegistrationID: regID,
Serial: serial,
Digest: digest,
DER: certDER,
Issued: *issued,
Expires: parsedCertificate.NotAfter,
}
isRenewalRaw, overallError := db.WithTransaction(ctx, ssa.dbMap, func(txWithCtx db.Executor) (interface{}, error) {
// Save the final certificate
err = txWithCtx.Insert(cert)
if err != nil {
if db.IsDuplicate(err) {
return nil, berrors.DuplicateError("cannot add a duplicate cert")
}
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 "", 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 "", 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)
if err := ssa.addCertificatesPerName(ctx, txWithCtx, parsedCertificate.DNSNames, timeToTheHour); err != nil {
return nil, err
}
}
// Update the FQDN sets now that there is a final certificate to ensure rate
// limits are calculated correctly.
if err := addFQDNSet(
txWithCtx,
parsedCertificate.DNSNames,
core.SerialToString(parsedCertificate.SerialNumber),
parsedCertificate.NotBefore,
parsedCertificate.NotAfter,
); 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 digest, nil
}
func (ssa *SQLStorageAuthority) CountOrders(ctx context.Context, acctID int64, earliest, latest time.Time) (int, error) {
var count int
err := ssa.dbMap.WithContext(ctx).SelectOne(&count,
`SELECT count(1) FROM orders
WHERE registrationID = :acctID AND
created >= :windowLeft AND
created < :windowRight`,
map[string]interface{}{
"acctID": acctID,
"windowLeft": earliest,
"windowRight": latest,
})
if err != nil {
return 0, err
}
return count, nil
}
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 returns the number of sets with hash |setHash| within the window
// |window|
func (ssa *SQLStorageAuthority) CountFQDNSets(ctx context.Context, window time.Duration, names []string) (int64, error) {
var count int64
err := ssa.dbMap.WithContext(ctx).SelectOne(
&count,
`SELECT COUNT(1) FROM fqdnSets
WHERE setHash = ?
AND issued > ?`,
hashNames(names),
ssa.clk.Now().Add(-window),
)
return count, err
}
// setHash is a []byte representing the hash of an FQDN Set
type setHash []byte
// getFQDNSetsBySerials finds the setHashes corresponding to a set of
// certificate serials. These serials can be used to check whether any
// certificates have been issued for the same set of names previously.
func (ssa *SQLStorageAuthority) getFQDNSetsBySerials(
dbMap db.Selector,
serials []string,
) ([]setHash, error) {
var fqdnSets []setHash
// It is unexpected that this function would be called with no serials
if len(serials) == 0 {
err := fmt.Errorf("getFQDNSetsBySerials called with no serials")
ssa.log.AuditErr(err.Error())
return nil, err
}
qmarks := make([]string, len(serials))
params := make([]interface{}, len(serials))
for i, serial := range serials {
params[i] = serial
qmarks[i] = "?"
}
query := "SELECT setHash FROM fqdnSets " +
"WHERE serial IN (" + strings.Join(qmarks, ",") + ")"
_, err := dbMap.Select(
&fqdnSets,
query,
params...)
if err != nil {
return nil, err
}
// The serials existed when we found them in issuedNames, they should continue
// to exist here. Otherwise an internal consistency violation occurred and
// needs to be audit logged
if db.IsNoRows(err) {
err := fmt.Errorf("getFQDNSetsBySerials returned no rows - internal consistency violation")
ssa.log.AuditErr(err.Error())
return nil, err
}
return fqdnSets, nil
}
// getNewIssuancesByFQDNSet returns a count of new issuances (renewals are not
// included) for a given slice of fqdnSets that occurred after the earliest
// parameter.
func (ssa *SQLStorageAuthority) getNewIssuancesByFQDNSet(
dbMap db.Selector,
fqdnSets []setHash,
earliest time.Time,
) (int, error) {
var results []struct {
Serial string
SetHash setHash
Issued time.Time
}
qmarks := make([]string, len(fqdnSets))
params := make([]interface{}, len(fqdnSets))
for i, setHash := range fqdnSets {
// We have to cast the setHash back to []byte here since the sql package
// isn't able to convert `sa.setHash` for the parameter value itself
params[i] = []byte(setHash)
qmarks[i] = "?"
}
query := "SELECT serial, setHash, issued FROM fqdnSets " +
"WHERE setHash IN (" + strings.Join(qmarks, ",") + ") " +
"ORDER BY setHash, issued"
// First, find the serial, sethash and issued date from the fqdnSets table for
// the given fqdn set hashes
_, err := dbMap.Select(
&results,
query,
params...)
if err != nil {
// If there are no results we have encountered a major error and
// should loudly complain
if db.IsNoRows(err) {
ssa.log.AuditErrf("Found no results from fqdnSets for setHashes known to exist: %#v", fqdnSets)
return 0, err
}
return -1, err
}
processedSetHashes := make(map[string]bool)
issuanceCount := 0
// Loop through each set hash result, counting issuances per unique set hash
// that are within the window specified by the earliest parameter
for _, result := range results {
key := string(result.SetHash)
// Skip set hashes that we have already processed - we only care about the
// first issuance
if processedSetHashes[key] {
continue
}
// If the issued date is before our earliest cutoff then skip it
if result.Issued.Before(earliest) {
continue
}
// Otherwise note the issuance and mark the set hash as processed
issuanceCount++
processedSetHashes[key] = true
}
// Return the count of how many non-renewal issuances there were
return issuanceCount, nil
}
// FQDNSetExists returns a bool indicating if one or more FQDN sets |names|
// exists in the database
func (ssa *SQLStorageAuthority) FQDNSetExists(ctx context.Context, names []string) (bool, error) {
exists, err := ssa.checkFQDNSetExists(
ssa.dbMap.WithContext(ctx).SelectOne,
names)
if err != nil {
return false, err
}
return 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) {
var count int64
err := selector(
&count,
`SELECT COUNT(1) FROM fqdnSets
WHERE setHash = ?
LIMIT 1`,
hashNames(names),
)
return count > 0, 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.
func (ssa *SQLStorageAuthority) PreviousCertificateExists(
ctx context.Context,
req *sapb.PreviousCertificateExistsRequest,
) (*sapb.Exists, error) {
t := true
exists := &sapb.Exists{Exists: &t}
f := false
notExists := &sapb.Exists{Exists: &f}
// 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, id int64) error {
_, err := ssa.dbMap.WithContext(ctx).Exec(
"UPDATE registrations SET status = ? WHERE status = ? AND id = ?",
string(core.StatusDeactivated),
string(core.StatusValid),
id,
)
return err
}
// 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) (*corepb.Empty, error) {
_, 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 &corepb.Empty{}, nil
}
// NewOrder adds a new v2 style order to the database
func (ssa *SQLStorageAuthority) NewOrder(ctx context.Context, req *corepb.Order) (*corepb.Order, error) {
order := &orderModel{
RegistrationID: *req.RegistrationID,
Expires: time.Unix(0, *req.Expires),
Created: ssa.clk.Now(),
}
output, overallError := db.WithTransaction(ctx, ssa.dbMap, func(txWithCtx db.Executor) (interface{}, error) {
if err := txWithCtx.Insert(order); err != nil {
return nil, err
}
for _, id := range req.V2Authorizations {
otoa := &orderToAuthz2Model{
OrderID: order.ID,
AuthzID: id,
}
if err := txWithCtx.Insert(otoa); err != nil {
return nil, err
}
}
for _, name := range req.Names {
reqdName := &requestedNameModel{
OrderID: order.ID,
ReversedName: ReverseName(name),
}
if err := txWithCtx.Insert(reqdName); err != nil {
return nil, err
}
}
// Add an FQDNSet entry for the order
if err := addOrderFQDNSet(
txWithCtx, req.Names, order.ID, order.RegistrationID, order.Expires); err != nil {
return nil, err
}
return req, nil
})
if overallError != nil {
return nil, overallError
}
var outputOrder *corepb.Order
var ok bool
if outputOrder, ok = output.(*corepb.Order); !ok {
return nil, fmt.Errorf("shouldn't happen: casting error in NewOrder")
}
// Update the output with the ID that the order received
outputOrder.Id = &order.ID
// Update the output with the created timestamp from the model
createdTS := order.Created.UnixNano()
outputOrder.Created = &createdTS
// A new order is never processing because it can't have been finalized yet
processingStatus := false
outputOrder.BeganProcessing = &processingStatus
// 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, outputOrder)
if err != nil {
return nil, err
}
outputOrder.Status = &status
return outputOrder, nil
}
// SetOrderProcessing updates a provided *corepb.Order in pending status to be
// in processing status by updating the `beganProcessing` field of the
// corresponding Order table row in the DB.
func (ssa *SQLStorageAuthority) SetOrderProcessing(ctx context.Context, req *corepb.Order) error {
_, overallError := db.WithTransaction(ctx, ssa.dbMap, func(txWithCtx db.Executor) (interface{}, error) {
result, err := txWithCtx.Exec(`
UPDATE orders
SET beganProcessing = ?
WHERE id = ?
AND beganProcessing = ?`,
true,
*req.Id,
false)
if err != nil {
return nil, berrors.InternalServerError("error updating order to beganProcessing status")
}
n, err := result.RowsAffected()
if err != nil || n == 0 {
return nil, berrors.OrderNotReadyError("Order was already processing. This may indicate your client finalized the same order multiple times, possibly due to a client bug.")
}
return nil, nil
})
return overallError
}
// SetOrderError updates a provided Order's error field.
func (ssa *SQLStorageAuthority) SetOrderError(ctx context.Context, order *corepb.Order) error {
_, overallError := db.WithTransaction(ctx, ssa.dbMap, func(txWithCtx db.Executor) (interface{}, error) {
om, err := orderToModel(order)
if err != nil {
return nil, err
}
result, err := txWithCtx.Exec(`
UPDATE orders
SET error = ?
WHERE id = ?`,
om.Error,
om.ID)
if err != nil {