forked from letsencrypt/boulder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sa.go
2091 lines (1884 loc) · 61.9 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 (
"crypto/sha256"
"crypto/x509"
"database/sql"
"encoding/json"
"errors"
"fmt"
"math/big"
"net"
"strings"
"sync"
"time"
"github.com/jmhodges/clock"
"golang.org/x/net/context"
"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"
berrors "github.com/letsencrypt/boulder/errors"
"github.com/letsencrypt/boulder/features"
bgrpc "github.com/letsencrypt/boulder/grpc"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/metrics"
"github.com/letsencrypt/boulder/revocation"
sapb "github.com/letsencrypt/boulder/sa/proto"
)
var ErrDuplicate = errors.New("cannot add a duplicate row")
type certCountFunc func(domain string, earliest, latest time.Time) (int, error)
type getChallengesFunc func(authID string) ([]core.Challenge, error)
// SQLStorageAuthority defines a Storage Authority
type SQLStorageAuthority struct {
dbMap *gorp.DbMap
clk clock.Clock
log blog.Logger
scope metrics.Scope
// 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
getChallenges getChallengesFunc
}
func digest256(data []byte) []byte {
d := sha256.New()
_, _ = d.Write(data) // Never returns an error
return d.Sum(nil)
}
// Utility models
type pendingauthzModel struct {
core.Authorization
LockCol int64
}
type authzModel struct {
core.Authorization
}
// 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 *gorp.DbMap,
clk clock.Clock,
logger blog.Logger,
scope metrics.Scope,
parallelismPerRPC int,
) (*SQLStorageAuthority, error) {
SetSQLDebug(dbMap, logger)
ssa := &SQLStorageAuthority{
dbMap: dbMap,
clk: clk,
log: logger,
scope: scope,
parallelismPerRPC: parallelismPerRPC,
}
ssa.countCertificatesByName = ssa.countCertificatesByNameImpl
ssa.getChallenges = ssa.getChallengesImpl
return ssa, nil
}
func statusIsPending(status core.AcmeStatus) bool {
return status == core.StatusPending || status == core.StatusProcessing || status == core.StatusUnknown
}
func existingPending(tx *gorp.Transaction, id string) bool {
var count int64
_ = tx.SelectOne(&count, "SELECT count(*) FROM pendingAuthorizations WHERE id = :id", map[string]interface{}{"id": id})
return count > 0
}
func existingFinal(tx *gorp.Transaction, id string) bool {
var count int64
_ = tx.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
}
func updateChallenges(authID string, challenges []core.Challenge, tx *gorp.Transaction) error {
var challs []challModel
_, err := tx.Select(
&challs,
getChallengesQuery,
map[string]interface{}{"authID": authID},
)
if err != nil {
return err
}
if len(challs) != len(challenges) {
return fmt.Errorf("Invalid number of challenges provided")
}
for i, authChall := range challenges {
chall, err := challengeToModel(&authChall, challs[i].AuthorizationID)
if err != nil {
return err
}
chall.ID = challs[i].ID
_, err = tx.Update(chall)
if err != nil {
return err
}
}
return nil
}
// 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, query, id)
if err == sql.ErrNoRows {
return core.Registration{}, berrors.NotFoundError("registration with ID '%d' not found", id)
}
if err != nil {
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, query, sha)
if err == sql.ErrNoRows {
return core.Registration{}, berrors.NotFoundError("no registrations with public key sha256 %q", sha)
}
if err != nil {
return core.Registration{}, err
}
return modelToRegistration(model)
}
// GetAuthorization obtains an Authorization by ID
func (ssa *SQLStorageAuthority) GetAuthorization(ctx context.Context, id string) (core.Authorization, error) {
authz := core.Authorization{}
tx, err := ssa.dbMap.Begin()
if err != nil {
return authz, err
}
pa, err := selectPendingAuthz(tx, "WHERE id = ?", id)
if err != nil && err != sql.ErrNoRows {
return authz, Rollback(tx, err)
}
if err == sql.ErrNoRows {
var fa authzModel
err := tx.SelectOne(&fa, fmt.Sprintf("SELECT %s FROM authz WHERE id = ?", authzFields), id)
if err != nil && err != sql.ErrNoRows {
return authz, Rollback(tx, err)
} else if err == sql.ErrNoRows {
// If there was no result in either the pending authz table or the authz
// table then return a `berrors.NotFound` instance (or a rollback error if
// the transaction rollback fails)
return authz, Rollback(
tx,
berrors.NotFoundError("no authorization found with id %q", id))
}
authz = fa.Authorization
} else {
authz = pa.Authorization
}
authz.Challenges, err = ssa.getChallenges(authz.ID)
if err != nil {
return authz, Rollback(tx, err)
}
return authz, tx.Commit()
}
// GetValidAuthorizations returns the latest authorization object for all
// domain names from the parameters that the account has authorizations for.
func (ssa *SQLStorageAuthority) GetValidAuthorizations(
ctx context.Context,
registrationID int64,
names []string,
now time.Time) (map[string]*core.Authorization, error) {
return ssa.getAuthorizations(
ctx,
authorizationTable,
string(core.StatusValid),
registrationID,
names,
now,
false)
}
// 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.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.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(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 (ssa *SQLStorageAuthority) CountCertificatesByExactNames(ctx context.Context, domains []string, earliest, latest time.Time) ([]*sapb.CountByNames_MapElement, error) {
var ret []*sapb.CountByNames_MapElement
for _, domain := range domains {
currentCount, err := ssa.countCertificatesByExactName(domain, earliest, latest)
if err != nil {
return ret, err
}
name := string(domain)
pbCount := int64(currentCount)
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, ".")
}
const countCertificatesSelect = `
SELECT serial from issuedNames
WHERE (reversedName = :reversedDomain OR
reversedName LIKE CONCAT(:reversedDomain, ".%"))
AND notBefore > :earliest AND notBefore <= :latest;`
const countCertificatesExactSelect = `
SELECT serial from issuedNames
WHERE reversedName = :reversedDomain
AND notBefore > :earliest AND notBefore <= :latest;`
// countCertificatesByNames returns, for a single domain, the count of
// certificates issued in the given time range for that domain and its
// subdomains.
func (ssa *SQLStorageAuthority) countCertificatesByNameImpl(domain string, earliest, latest time.Time) (int, error) {
return ssa.countCertificates(domain, earliest, latest, countCertificatesSelect)
}
// countCertificatesByExactNames returns, for a single domain, the count of
// certificates issued in the given time range for that domain. In contrast to
// countCertificatesByNames subdomains are NOT considered.
func (ssa *SQLStorageAuthority) countCertificatesByExactName(domain string, earliest, latest time.Time) (int, error) {
return ssa.countCertificates(domain, earliest, latest, countCertificatesExactSelect)
}
// countCertificates returns, for a single domain, the count of
// non-renewal certificate issuances in the given time range for that domain using the
// provided query, assumed to be either `countCertificatesExactSelect` or
// `countCertificatesSelect`. If the `AllowRenewalFirstRL` feature flag is set,
// renewals of certificates issued within the same window are considered "free"
// and are not counted.
func (ssa *SQLStorageAuthority) countCertificates(domain string, earliest, latest time.Time, query string) (int, error) {
var serials []string
_, err := ssa.dbMap.Select(
&serials,
query,
map[string]interface{}{
"reversedDomain": ReverseName(domain),
"earliest": earliest,
"latest": latest,
})
if err == sql.ErrNoRows {
return 0, nil
} else if err != nil {
return 0, err
}
// If the `AllowRenewalFirstRL` feature flag is enabled then do the work
// required to discount renewals
if features.Enabled(features.AllowRenewalFirstRL) {
// If there are no serials found, short circuit since there isn't subsequent
// work to do
if len(serials) == 0 {
return 0, nil
}
// Find all FQDN Set Hashes with the serials from the issuedNames table that
// were visible within our search window
fqdnSets, err := ssa.getFQDNSetsBySerials(serials)
if err != nil {
return 0, err
}
// Using those FQDN Set Hashes, we can then find all of the non-renewal
// issuances with a second query against the fqdnSets table using the set
// hashes we know about
nonRenewalIssuances, err := ssa.getNewIssuancesByFQDNSet(fqdnSets, earliest)
if err != nil {
return 0, err
}
return nonRenewalIssuances, nil
} else {
// Otherwise, use the preexisting behaviour and deduplicate by serials
// returning a count of unique serials qignoring any potential renewals
serialMap := make(map[string]struct{}, len(serials))
for _, s := range serials {
serialMap[s] = struct{}{}
}
return len(serialMap), nil
}
}
// 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, "WHERE serial = ?", serial)
if err == sql.ErrNoRows {
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
}
var status core.CertificateStatus
statusObj, err := ssa.dbMap.Get(certStatusModel{}, serial)
if err != nil {
return status, err
}
if statusObj == nil {
return status, nil
}
statusModel := statusObj.(*certStatusModel)
status = 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,
}
return status, 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.Insert(rm)
if err != nil {
return reg, err
}
return modelToRegistration(rm)
}
// MarkCertificateRevoked stores the fact that a certificate is revoked, along
// with a timestamp and a reason.
func (ssa *SQLStorageAuthority) MarkCertificateRevoked(ctx context.Context, serial string, reasonCode revocation.Reason) error {
var err error
if _, err = ssa.GetCertificate(ctx, serial); err != nil {
return fmt.Errorf(
"Unable to mark certificate %s revoked: cert not found.", serial)
}
if _, err = ssa.GetCertificateStatus(ctx, serial); err != nil {
return fmt.Errorf(
"Unable to mark certificate %s revoked: cert status not found.", serial)
}
tx, err := ssa.dbMap.Begin()
if err != nil {
return err
}
const statusQuery = "WHERE serial = ?"
statusObj, err := SelectCertificateStatus(tx, statusQuery, serial)
if err == sql.ErrNoRows {
err = fmt.Errorf("No certificate with serial %s", serial)
err = Rollback(tx, err)
return err
}
if err != nil {
err = Rollback(tx, err)
return err
}
var n int64
now := ssa.clk.Now()
statusObj.Status = core.OCSPStatusRevoked
statusObj.RevokedDate = now
statusObj.RevokedReason = reasonCode
n, err = tx.Update(&statusObj)
if err != nil {
err = Rollback(tx, err)
return err
}
if n == 0 {
err = berrors.InternalServerError("no certificate updated")
err = Rollback(tx, err)
return err
}
return tx.Commit()
}
// 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, query, reg.ID)
if err == sql.ErrNoRows {
return berrors.NotFoundError("registration with ID '%d' not found", reg.ID)
}
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.Update(updatedRegModel)
if err != nil {
return err
}
if n == 0 {
return berrors.NotFoundError("registration with ID '%d' not found", reg.ID)
}
return nil
}
// NewPendingAuthorization retrieves a pending authorization for
// authz.Identifier if one exists, or creates a new one otherwise.
func (ssa *SQLStorageAuthority) NewPendingAuthorization(ctx context.Context, authz core.Authorization) (core.Authorization, error) {
var output core.Authorization
tx, err := ssa.dbMap.Begin()
if err != nil {
return output, err
}
// Create a random ID and check that it doesn't exist already
authz.ID = core.NewToken()
for existingPending(tx, authz.ID) || existingFinal(tx, authz.ID) {
authz.ID = core.NewToken()
}
// Insert a stub row in pending
pendingAuthz := pendingauthzModel{Authorization: authz}
err = tx.Insert(&pendingAuthz)
if err != nil {
err = Rollback(tx, err)
return output, err
}
for i, c := range authz.Challenges {
challModel, err := challengeToModel(&c, pendingAuthz.ID)
if err != nil {
err = Rollback(tx, err)
return output, err
}
// Magic happens here: Gorp will modify challModel, setting challModel.ID
// to the auto-increment primary key. This is important because we want
// the challenge objects inside the Authorization we return to know their
// IDs, so they can have proper URLs.
// See https://godoc.org/github.com/coopernurse/gorp#DbMap.Insert
err = tx.Insert(challModel)
if err != nil {
err = Rollback(tx, err)
return output, err
}
challenge, err := modelToChallenge(challModel)
if err != nil {
err = Rollback(tx, err)
return output, err
}
authz.Challenges[i] = challenge
}
err = tx.Commit()
output = pendingAuthz.Authorization
output.Challenges = authz.Challenges
return output, err
}
// GetPendingAuthorization returns the most recent Pending authorization
// with the given identifier, if available.
func (ssa *SQLStorageAuthority) GetPendingAuthorization(
ctx context.Context,
req *sapb.GetPendingAuthorizationRequest,
) (*core.Authorization, error) {
identifierJSON, err := json.Marshal(core.AcmeIdentifier{
Type: core.IdentifierType(*req.IdentifierType),
Value: *req.IdentifierValue,
})
if err != nil {
return nil, err
}
// Note: This will use the index on `registrationId`, `expires`, which should
// keep the amount of scanning to a minimum. That index does not include the
// identifier, so accounts with huge numbers of pending authzs may result in
// slow queries here.
pa, err := selectPendingAuthz(ssa.dbMap,
`WHERE registrationID = :regID
AND identifier = :identifierJSON
AND status = :status
AND expires > :validUntil
ORDER BY expires ASC
LIMIT 1`,
map[string]interface{}{
"regID": *req.RegistrationID,
"identifierJSON": identifierJSON,
"status": string(core.StatusPending),
"validUntil": time.Unix(0, *req.ValidUntil),
})
if err == sql.ErrNoRows {
return nil, berrors.NotFoundError("pending authz not found")
} else if err == nil {
// We found an authz, but we still need to fetch its challenges. To
// simplify things, just call GetAuthorization, which takes care of that.
ssa.scope.Inc("reused_authz", 1)
authz, err := ssa.GetAuthorization(ctx, pa.ID)
return &authz, err
} else {
// Any error other than ErrNoRows; return the error
return nil, err
}
}
// UpdatePendingAuthorization updates a Pending Authorization's Challenges.
// Despite what the name "UpdatePendingAuthorization" (preserved for legacy
// reasons) may indicate, the pending authorization table row is not changed,
// only the associated challenges by way of `sa.updateChallenges`.
func (ssa *SQLStorageAuthority) UpdatePendingAuthorization(ctx context.Context, authz core.Authorization) error {
tx, err := ssa.dbMap.Begin()
if err != nil {
return err
}
if !statusIsPending(authz.Status) {
err = berrors.WrongAuthorizationStateError("authorization is not pending")
return Rollback(tx, err)
}
if existingFinal(tx, authz.ID) {
err = berrors.WrongAuthorizationStateError("cannot update a finalized authorization")
return Rollback(tx, err)
}
if !existingPending(tx, authz.ID) {
err = berrors.InternalServerError("authorization with ID '%d' not found", authz.ID)
return Rollback(tx, err)
}
_, err = selectPendingAuthz(tx, "WHERE id = ?", authz.ID)
if err == sql.ErrNoRows {
err = berrors.InternalServerError("authorization with ID '%d' not found", authz.ID)
return Rollback(tx, err)
}
if err != nil {
return Rollback(tx, err)
}
err = updateChallenges(authz.ID, authz.Challenges, tx)
if err != nil {
return Rollback(tx, err)
}
return tx.Commit()
}
// FinalizeAuthorization converts a Pending Authorization to a final one. If the
// Authorization is not found a berrors.NotFound result is returned. If the
// Authorization is status pending a berrors.InternalServer error is returned.
func (ssa *SQLStorageAuthority) FinalizeAuthorization(ctx context.Context, authz core.Authorization) error {
tx, err := ssa.dbMap.Begin()
if err != nil {
return err
}
// Check that a pending authz exists
if !existingPending(tx, authz.ID) {
err = berrors.NotFoundError("authorization with ID %q not found", authz.ID)
return Rollback(tx, err)
}
if statusIsPending(authz.Status) {
err = berrors.InternalServerError("authorization to finalize is pending (ID %q)", authz.ID)
return Rollback(tx, err)
}
auth := &authzModel{authz}
pa, err := selectPendingAuthz(tx, "WHERE id = ?", authz.ID)
if err == sql.ErrNoRows {
return Rollback(tx, berrors.NotFoundError("authorization with ID %q not found", authz.ID))
}
if err != nil {
return Rollback(tx, err)
}
err = tx.Insert(auth)
if err != nil {
return Rollback(tx, err)
}
_, err = tx.Delete(pa)
if err != nil {
return Rollback(tx, err)
}
err = updateChallenges(authz.ID, authz.Challenges, tx)
if err != nil {
return Rollback(tx, err)
}
return tx.Commit()
}
// RevokeAuthorizationsByDomain invalidates all pending or finalized authorizations
// for a specific domain
func (ssa *SQLStorageAuthority) RevokeAuthorizationsByDomain(ctx context.Context, ident core.AcmeIdentifier) (int64, int64, error) {
identifierJSON, err := json.Marshal(ident)
if err != nil {
return 0, 0, err
}
identifier := string(identifierJSON)
results := []int64{0, 0}
now := ssa.clk.Now()
for i, table := range authorizationTables {
for {
authz, err := getAuthorizationIDsByDomain(ssa.dbMap, table, identifier, now)
if err != nil {
return results[0], results[1], err
}
numAuthz := len(authz)
if numAuthz == 0 {
break
}
numRevoked, err := revokeAuthorizations(ssa.dbMap, table, authz)
if err != nil {
return results[0], results[1], err
}
results[i] += numRevoked
if numRevoked < int64(numAuthz) {
return results[0], results[1], fmt.Errorf("Didn't revoke all found authorizations")
}
}
}
return results[0], results[1], 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,
}
certStatus := &certStatusModel{
Status: core.OCSPStatus("good"),
OCSPLastUpdated: time.Time{},
OCSPResponse: []byte{},
Serial: serial,
RevokedDate: time.Time{},
RevokedReason: 0,
NotAfter: parsedCertificate.NotAfter,
}
if len(ocspResponse) != 0 {
certStatus.OCSPResponse = ocspResponse
certStatus.OCSPLastUpdated = ssa.clk.Now()
}
tx, err := ssa.dbMap.Begin()
if err != nil {
return "", err
}
// Note: will fail on duplicate serials. Extremely unlikely to happen and soon
// to be fixed by redesign. Reference issue
// https://github.com/letsencrypt/boulder/issues/2265 for more
err = tx.Insert(cert)
if err != nil {
if strings.HasPrefix(err.Error(), "Error 1062: Duplicate entry") {
err = ErrDuplicate
}
return "", Rollback(tx, err)
}
err = tx.Insert(certStatus)
if err != nil {
if strings.HasPrefix(err.Error(), "Error 1062: Duplicate entry") {
err = ErrDuplicate
}
return "", Rollback(tx, err)
}
err = addIssuedNames(tx, parsedCertificate)
if err != nil {
return "", Rollback(tx, err)
}
err = addFQDNSet(
tx,
parsedCertificate.DNSNames,
serial,
parsedCertificate.NotBefore,
parsedCertificate.NotAfter,
)
if err != nil {
return "", Rollback(tx, err)
}
return digest, tx.Commit()
}
// CountPendingAuthorizations returns the number of pending, unexpired
// authorizations for the given registration.
func (ssa *SQLStorageAuthority) CountPendingAuthorizations(ctx context.Context, regID int64) (count int, err error) {
err = ssa.dbMap.SelectOne(&count,
`SELECT count(1) FROM pendingAuthorizations
WHERE registrationID = :regID AND
expires > :now AND
status = :pending`,
map[string]interface{}{
"regID": regID,
"now": ssa.clk.Now(),
"pending": string(core.StatusPending),
})
return
}
func (ssa *SQLStorageAuthority) CountOrders(ctx context.Context, acctID int64, earliest, latest time.Time) (int, error) {
var count int
err := ssa.dbMap.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 {