This repository has been archived by the owner on Jun 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
queries.go
463 lines (396 loc) · 11.7 KB
/
queries.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
package persistence
import (
"database/sql"
"fmt"
"time"
pb "github.com/CovidShield/server/pkg/proto/covidshield"
"github.com/CovidShield/server/pkg/timemath"
)
const (
MaxConsecutiveClaimKeyFailures = 8
claimKeyBanDuration = 1 * time.Hour
)
// (Legal requirement: <21)
// We serve up the last 14. This number 15 includes the current day, so 14 days
// ago is the oldest data.
const maxDiagnosisKeyRetentionDays = 15
// A generated keypair can upload up to 28 keys (14 on day 1, plus 14
// subsequent days)
const initialRemainingKeys = 28
// (Legal requirement: <21)
// When we assign an Application Public Key to a server keypair, we reset the
// created timestamp to the beginning of its existing UTC date. (i.e.
// subtracting anywhere from 00:00 to 23:59 from it)
//
// From that timestamp, the Application may submit keys for up to 15 days,
// which really means they should submit keys for up to 14 days.
const encryptionKeyValidityDays = 15
// OneTimeCodes must be used within 1440 minutes, otherwise they expire.
const oneTimeCodeExpiryInMinutes = 1440
func deleteOldDiagnosisKeys(db *sql.DB) (int64, error) {
oldestDateNumber := timemath.DateNumber(time.Now()) - maxDiagnosisKeyRetentionDays
oldestHour := timemath.HourNumberAtStartOfDate(oldestDateNumber)
res, err := db.Exec(`DELETE FROM diagnosis_keys WHERE hour_of_submission < ?`, oldestHour)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Delete anything past our data retention threshold, AND any timed-out KeyClaims.
func deleteOldEncryptionKeys(db *sql.DB) (int64, error) {
res, err := db.Exec(
fmt.Sprintf(`
DELETE FROM encryption_keys
WHERE (created < (NOW() - INTERVAL %d DAY))
OR ((created < (NOW() - INTERVAL %d MINUTE)) AND app_public_key IS NULL)
OR remaining_keys = 0
`, encryptionKeyValidityDays, oneTimeCodeExpiryInMinutes),
)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
func claimKey(db *sql.DB, oneTimeCode string, appPublicKey []byte) ([]byte, error) {
tx, err := db.Begin()
if err != nil {
return nil, err
}
var exists int
if err := tx.QueryRow("SELECT COUNT(*) FROM encryption_keys WHERE app_public_key = ?", appPublicKey).Scan(&exists); err != nil {
if err := tx.Rollback(); err != nil {
return nil, err
}
return nil, err
}
if exists == 1 {
if err := tx.Rollback(); err != nil {
return nil, err
}
return nil, ErrDuplicateKey
}
var created time.Time
if err := tx.QueryRow("SELECT created FROM encryption_keys WHERE one_time_code = ?", oneTimeCode).Scan(&created); err != nil {
if err := tx.Rollback(); err != nil {
return nil, err
}
return nil, ErrInvalidOneTimeCode
}
created = timemath.MostRecentUTCMidnight(created)
if created.Unix() == int64(0) {
if err := tx.Rollback(); err != nil {
return nil, err
}
return nil, ErrInvalidOneTimeCode
}
s, err := tx.Prepare(
fmt.Sprintf(
`UPDATE encryption_keys
SET one_time_code = NULL,
app_public_key = ?,
created = ?
WHERE one_time_code = ?
AND created > (NOW() - INTERVAL %d MINUTE)`,
oneTimeCodeExpiryInMinutes,
),
)
if err != nil {
if err := tx.Rollback(); err != nil {
return nil, err
}
return nil, err
}
res, err := s.Exec(appPublicKey, created, oneTimeCode)
if err != nil {
if err := tx.Rollback(); err != nil {
return nil, err
}
return nil, err
}
n, err := res.RowsAffected()
if err != nil {
if err := tx.Rollback(); err != nil {
return nil, err
}
return nil, err
}
if n != 1 {
if err := tx.Rollback(); err != nil {
return nil, err
}
return nil, ErrInvalidOneTimeCode
}
s, err = tx.Prepare(
`SELECT server_public_key FROM encryption_keys WHERE app_public_key = ?`,
)
if err != nil {
if err := tx.Rollback(); err != nil {
return nil, err
}
return nil, err
}
row := s.QueryRow(appPublicKey)
var serverPub []byte
if err := row.Scan(&serverPub); err != nil {
if err := tx.Rollback(); err != nil {
return nil, err
}
return nil, err
}
if err = tx.Commit(); err != nil {
return nil, err
}
return serverPub, nil
}
func persistEncryptionKey(db *sql.DB, region, originator, hashID string, pub *[32]byte, priv *[32]byte, oneTimeCode string) error {
_, err := db.Exec(
`INSERT INTO encryption_keys
(region, originator, hash_id, server_private_key, server_public_key, one_time_code, remaining_keys)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
region, originator, hashID, priv[:], pub[:], oneTimeCode, initialRemainingKeys,
)
return err
}
func privForPub(db *sql.DB, pub []byte) *sql.Row {
return db.QueryRow(fmt.Sprintf(`
SELECT server_private_key FROM encryption_keys
WHERE server_public_key = ?
AND created > (NOW() - INTERVAL %d DAY)
LIMIT 1`,
encryptionKeyValidityDays,
),
pub,
)
}
// Return keys that were SUBMITTED to the Diagnosis Server during the specified
// UTC date.
//
// Only return keys that correspond to a Key valid for a date less than 14 days ago.
//
// TODO: this might be the right place to pad inappropriately small batches
func diagnosisKeysForDateNumber(db *sql.DB, region string, dateNumber uint32, currentRollingStartIntervalNumber int32) (*sql.Rows, error) {
startHour := dateNumber * 24
endHour := startHour + 24
minRollingStartIntervalNumber := timemath.RollingStartIntervalNumberPlusDays(currentRollingStartIntervalNumber, -14)
return db.Query(
`SELECT region, key_data, rolling_start_interval_number, rolling_period, transmission_risk_level FROM diagnosis_keys
WHERE hour_of_submission >= ?
AND hour_of_submission < ?
AND rolling_start_interval_number > ?
AND region = ?
ORDER BY key_data
`, // don't implicitly order by insertion date: for privacy
startHour, endHour, minRollingStartIntervalNumber, region,
)
}
func postDateKeyIfNecessary(hourOfSubmission uint32, key *pb.TemporaryExposureKey) uint32 {
// ENIntervalNumber at which the key became inactive
keyEnd := key.GetRollingStartIntervalNumber() + key.GetRollingPeriod()
// ENIntervalNumber at which we can safely serve the key
canServeAt := keyEnd + (144/24)*2
// interval to hour
minBoundForHour := uint32(canServeAt / 6)
if minBoundForHour > hourOfSubmission {
log(nil, nil).WithField("distance", minBoundForHour-hourOfSubmission).Info("post-dating key")
return minBoundForHour
}
return hourOfSubmission
}
func registerDiagnosisKeys(db *sql.DB, appPubKey *[32]byte, keys []*pb.TemporaryExposureKey) error {
tx, err := db.Begin()
if err != nil {
return err
}
var region string
var originator string
if err := tx.QueryRow("SELECT region, originator FROM encryption_keys WHERE app_public_key = ?", appPubKey[:]).Scan(®ion, &originator); err != nil {
if err := tx.Rollback(); err != nil {
return err
}
return err
}
s, err := tx.Prepare(`
INSERT IGNORE INTO diagnosis_keys
(region, originator, key_data, rolling_start_interval_number, rolling_period, transmission_risk_level, hour_of_submission)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
)
if err != nil {
if err := tx.Rollback(); err != nil {
return err
}
return err
}
hourOfSubmission := timemath.HourNumber(time.Now())
var keysInserted int64
for _, key := range keys {
hourForKey := postDateKeyIfNecessary(hourOfSubmission, key)
result, err := s.Exec(region, originator, key.GetKeyData(), key.GetRollingStartIntervalNumber(), key.GetRollingPeriod(), key.GetTransmissionRiskLevel(), hourForKey)
if err != nil {
if err := tx.Rollback(); err != nil {
return err
}
return err
}
n, err := result.RowsAffected()
if err != nil {
if err := tx.Rollback(); err != nil {
return err
}
return err
}
keysInserted += n
}
res, err := tx.Exec(`
UPDATE encryption_keys
SET remaining_keys = remaining_keys - ?
WHERE remaining_keys >= ?
AND app_public_key = ?`,
keysInserted,
keysInserted,
appPubKey[:],
)
if err != nil {
if err := tx.Rollback(); err != nil {
return err
}
return ErrTooManyKeys
}
n, err := res.RowsAffected()
if err != nil {
if err := tx.Rollback(); err != nil {
return err
}
return err
}
if n == 0 {
var remaining int
if err := tx.QueryRow("SELECT remaining_keys FROM encryption_keys WHERE app_public_key = ?", appPubKey[:]).Scan(&remaining); err != nil {
if err := tx.Rollback(); err != nil {
return err
}
return err
}
if remaining == 0 {
if err := tx.Rollback(); err != nil {
return err
}
return ErrKeyConsumed
}
}
if err = tx.Commit(); err != nil {
return err
}
return nil
}
type queryRower interface {
QueryRow(query string, args ...interface{}) *sql.Row
}
func checkClaimKeyBan(db queryRower, identifier string) (triesRemaining int, banDuration time.Duration, err error) {
var failures uint16
var lastFailure time.Time
q := db.QueryRow(`SELECT failures, last_failure FROM failed_key_claim_attempts WHERE identifier = ?`, identifier)
if err := q.Scan(&failures, &lastFailure); err != nil {
if err.Error() == "sql: no rows in result set" {
return MaxConsecutiveClaimKeyFailures, 0, nil
}
return 0, 0, err
}
triesRemaining = MaxConsecutiveClaimKeyFailures - int(failures)
if triesRemaining < 0 {
triesRemaining = 0
}
banDuration = time.Duration(0)
if triesRemaining == 0 {
elapsed := time.Since(lastFailure)
banDuration = claimKeyBanDuration - elapsed
}
if banDuration < time.Duration(0) {
return MaxConsecutiveClaimKeyFailures, 0, nil
}
return triesRemaining, banDuration, nil
}
func checkHashID(db *sql.DB, identifier string) (int64, error) {
var one_time_code string
row := db.QueryRow("SELECT one_time_code FROM encryption_keys WHERE hash_id = ?", identifier)
switch err := row.Scan(&one_time_code); {
case err == sql.ErrNoRows: // no hashID found
return 0, err
case len(one_time_code) == 0: // used hashID found
return 1, err
case len(one_time_code) > 0: // un-used hashID found
_, err = db.Exec(`DELETE FROM encryption_keys WHERE hash_id = ? AND one_time_code IS NOT NULL`, identifier)
if err != nil {
return 1, err
}
return 0, err
default:
return 1, err
}
}
func registerClaimKeySuccess(db *sql.DB, identifier string) error {
_, err := db.Exec(`DELETE FROM failed_key_claim_attempts WHERE identifier = ?`, identifier)
return err
}
func registerClaimKeyFailure(db *sql.DB, identifier string) (triesRemaining int, banDuration time.Duration, err error) {
tx, err := db.Begin()
if err != nil {
return 0, 0, err
}
if _, err := tx.Exec(`
INSERT INTO failed_key_claim_attempts (identifier) VALUES (?)
ON DUPLICATE KEY UPDATE
failures = failures + 1,
last_failure = NOW()
`, identifier); err != nil {
if err := tx.Rollback(); err != nil {
return 0, 0, err
}
return 0, 0, err
}
triesRemaining, banDuration, err = checkClaimKeyBan(tx, identifier)
if err != nil {
if err := tx.Rollback(); err != nil {
return 0, 0, err
}
return 0, 0, err
}
if err := tx.Commit(); err != nil {
return 0, 0, err
}
return triesRemaining, banDuration, nil
}
func deleteOldFailedClaimKeyAttempts(db *sql.DB) (int64, error) {
threshold := time.Now().Add(-claimKeyBanDuration)
res, err := db.Exec(`DELETE FROM failed_key_claim_attempts WHERE last_failure < ?`, threshold)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
func countClaimedOneTimeCodes(db *sql.DB) (int64, error) {
var count int64
row := db.QueryRow("SELECT COUNT(*) FROM encryption_keys WHERE one_time_code IS NULL")
err := row.Scan(&count)
if err != nil {
return -1, err
}
return count, err
}
func countDiagnosisKeys(db *sql.DB) (int64, error) {
var count int64
row := db.QueryRow("SELECT COUNT(*) FROM diagnosis_keys")
err := row.Scan(&count)
if err != nil {
return -1, err
}
return count, err
}
func countUnclaimedOneTimeCodes(db *sql.DB) (int64, error) {
var count int64
row := db.QueryRow("SELECT COUNT(*) FROM encryption_keys WHERE one_time_code IS NOT NULL")
err := row.Scan(&count)
if err != nil {
return -1, err
}
return count, err
}