/
scanproofs.go
500 lines (434 loc) · 11.7 KB
/
scanproofs.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
// Copyright 2016 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package engine
import (
"bufio"
"encoding/csv"
"encoding/gob"
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
"github.com/keybase/client/go/libkb"
keybase1 "github.com/keybase/client/go/protocol/keybase1"
)
type ScanProofsCacheData struct {
// Map from sigid to whether the proof is ok.
Proofs map[string]bool
}
type ScanProofsCache struct {
data ScanProofsCacheData
dirty bool
}
func NewScanProofsCache() *ScanProofsCache {
return &ScanProofsCache{
data: ScanProofsCacheData{
Proofs: make(map[string]bool),
},
dirty: false,
}
}
func LoadScanProofsCache(filepath string) (*ScanProofsCache, error) {
f, err := os.Open(filepath)
if err != nil {
return nil, err
}
dec := gob.NewDecoder(f)
var c ScanProofsCache
err = dec.Decode(&c.data)
if err != nil {
return nil, err
}
return &c, nil
}
func (c *ScanProofsCache) Get(sigID string) bool {
return c.data.Proofs[sigID]
}
func (c *ScanProofsCache) Set(sigID string) {
if !c.data.Proofs[sigID] {
c.dirty = true
}
c.data.Proofs[sigID] = true
}
func (c *ScanProofsCache) Save(filepath string) error {
if !c.dirty {
// Don't save if nothing has changed
return nil
}
temppath, f, err := libkb.OpenTempFile(filepath, "", 0644)
if err != nil {
return err
}
enc := gob.NewEncoder(f)
err = enc.Encode(c.data)
if err != nil {
f.Close()
return err
}
f.Close()
err = os.Rename(temppath, filepath)
if err != nil {
return err
}
c.dirty = false
return nil
}
type ScanProofsTickers map[keybase1.ProofType]*time.Ticker
type ScanProofsEngine struct {
libkb.Contextified
infile string
indices string
sigid string
ratelimit int
cachefile string
ignorefile string
}
var _ Engine2 = (*ScanProofsEngine)(nil)
func NewScanProofsEngine(infile string, indices string, sigid string, ratelimit int, cachefile string, ignorefile string, g *libkb.GlobalContext) *ScanProofsEngine {
return &ScanProofsEngine{
infile: infile,
indices: indices,
sigid: sigid,
ratelimit: ratelimit,
cachefile: cachefile,
ignorefile: ignorefile,
Contextified: libkb.NewContextified(g),
}
}
func (e *ScanProofsEngine) Name() string {
return "ScanProofs"
}
func (e *ScanProofsEngine) Prereqs() Prereqs {
return Prereqs{}
}
func (e *ScanProofsEngine) RequiredUIs() []libkb.UIKind {
return []libkb.UIKind{
libkb.LogUIKind,
}
}
func (e *ScanProofsEngine) SubConsumers() []libkb.UIConsumer {
return []libkb.UIConsumer{}
}
func (e *ScanProofsEngine) Run(m libkb.MetaContext) (err error) {
defer m.Trace("ScanProofsEngine#Run", &err)()
var cache *ScanProofsCache
saveevery := 10
var ignored []string
if len(e.cachefile) > 0 {
lcache, err := LoadScanProofsCache(e.cachefile)
if err == nil {
m.Info("Using cache: %v (%v entries)", e.cachefile, len(lcache.data.Proofs))
cache = lcache
} else {
m.Warning("Could not load cache: %v", err)
cache = NewScanProofsCache()
}
}
if len(e.ignorefile) > 0 {
ignored, err = LoadScanProofsIgnore(e.ignorefile)
if err != nil {
return fmt.Errorf("Could not open ignore file: %v", err)
}
m.Info("Using ignore file: %v (%v entries)", e.ignorefile, len(ignored))
}
if len(e.sigid) > 0 && len(e.indices) > 0 {
return fmt.Errorf("Only one of sigid and indices allowed")
}
// One ticker for each proof type.
var tickers = make(map[keybase1.ProofType]*time.Ticker)
m.Info("Running with ratelimit: %v ms", e.ratelimit)
if e.ratelimit < 0 {
return fmt.Errorf("Ratelimit value can not be negative: %v", e.ratelimit)
}
if e.ratelimit > 0 {
for _, ptype := range keybase1.ProofTypeMap {
switch ptype {
case keybase1.ProofType_GENERIC_WEB_SITE, keybase1.ProofType_DNS:
// Web sites and DNS do not need a rate limit.
default:
tickers[ptype] = time.NewTicker(time.Millisecond * time.Duration(e.ratelimit))
}
}
}
defer func(tickers *map[keybase1.ProofType]*time.Ticker) {
for _, ticker := range *tickers {
if ticker != nil {
ticker.Stop()
}
}
}(&tickers)
f, err := os.Open(e.infile)
if err != nil {
return err
}
r := csv.NewReader(f)
var records []map[string]string
header, err := r.Read()
if err != nil {
return fmt.Errorf("Could not read header: %v", err)
}
m.Debug("Reading csv... ")
for {
rec, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return err
}
record := make(map[string]string)
for i, val := range rec {
record[header[i]] = val
}
records = append(records, record)
}
m.Debug("done")
startindex := 0
endindex := len(records)
if len(e.indices) > 0 {
startindex, endindex, err = e.ParseIndices(e.indices)
if err != nil {
return err
}
}
if startindex < 0 {
return fmt.Errorf("Invalid start index: %v", startindex)
}
if endindex > len(records) {
return fmt.Errorf("Invalid end index: %v (%v records)", endindex, len(records))
}
nrun := 0
nok := 0
for i := startindex; i < endindex; i++ {
rec := records[i]
if len(e.sigid) > 0 && e.sigid != rec["sig_id"] {
continue
}
m.Info("i:%v user:%v type:%v sigid:%v", i, rec["username"], rec["proof_type"], rec["sig_id"])
err := e.ProcessOne(m, i, rec, cache, ignored, tickers)
nrun++
if err == nil {
m.Info("Ok\n")
nok++
if cache != nil {
cache.Set(rec["sig_id"])
if i%saveevery == 0 {
saveerr := cache.Save(e.cachefile)
if saveerr != nil {
m.Warning("Could not save cache: %v", saveerr)
}
}
}
} else {
m.Error("%v FAILED: %v\n", i, err)
}
}
m.Info("---")
m.Info("proofs checked : %v", nrun)
m.Info("oks : %v", nok)
m.Info("fails : %v", nrun-nok)
if cache != nil {
saveerr := cache.Save(e.cachefile)
if saveerr != nil {
m.Warning("Could not save cache: %v", saveerr)
}
}
return nil
}
func (e *ScanProofsEngine) ProcessOne(m libkb.MetaContext, i int, rec map[string]string, cache *ScanProofsCache, ignored []string, tickers ScanProofsTickers) error {
serverstate, err := strconv.Atoi(rec["state"])
if err != nil {
return fmt.Errorf("Could not read server state: %v", err)
}
shouldsucceed := true
skip := false
var skipreason string
badstate := false
switch keybase1.ProofState(serverstate) {
case keybase1.ProofState_NONE:
badstate = true
case keybase1.ProofState_OK:
case keybase1.ProofState_TEMP_FAILURE:
shouldsucceed = false
case keybase1.ProofState_PERM_FAILURE:
shouldsucceed = false
case keybase1.ProofState_LOOKING:
skip = true
skipreason = "server LOOKING"
case keybase1.ProofState_SUPERSEDED:
skip = true
skipreason = "server SUPERSEDED"
case keybase1.ProofState_POSTED:
badstate = true
case keybase1.ProofState_REVOKED:
skip = true
skipreason = "server REVOKED"
case keybase1.ProofState_DELETED:
skip = true
skipreason = "server DELETED"
default:
badstate = true
}
if cache != nil && cache.Get(rec["sig_id"]) {
skip = true
skipreason = "cached success"
}
for _, x := range ignored {
if x == rec["sig_id"] {
skip = true
skipreason = "in ignored list"
}
}
if badstate {
return fmt.Errorf("Unsupported serverstate: %v", serverstate)
}
if skip {
m.Info("skipping: %v", skipreason)
return nil
}
deluserstr := "Error loading user: Deleted"
perr1, foundhint1, err := e.CheckOne(m, rec, tickers)
if err != nil {
if err.Error() == deluserstr {
m.Info("deleted user")
return nil
}
return err
}
// Skip the rate limit on the second check.
perr2, foundhint2, err := e.CheckOne(m, rec, nil)
if err != nil {
return err
}
if foundhint1 != foundhint2 {
return fmt.Errorf("Local verifiers disagree: foundhint1:%v foundhint:%v (likely timing)",
foundhint1, foundhint2)
}
if (perr1 == nil) != (perr2 == nil) {
return fmt.Errorf("Local verifiers disagree:\n %v\n %v", perr1, perr2)
}
succeeded := foundhint1 && (perr1 == nil)
if succeeded != shouldsucceed {
return fmt.Errorf("Local verifiers disagree with server: server:%v client:%v", serverstate, perr1)
}
return nil
}
// CheckOne checks one proof using two checkers (default, pvl).
// NOTE: This doesn't make sense anymore because pvl is the default.
// Returns nil or an error, whether a hint was found, and any more serious error
func (e *ScanProofsEngine) CheckOne(m libkb.MetaContext, rec map[string]string, tickers ScanProofsTickers) (libkb.ProofError, bool, error) {
uid := keybase1.UID(rec["uid"])
sigid := keybase1.SigID(rec["sig_id"])
foundhint := false
hint, err := e.GetSigHint(m, uid, sigid)
if err != nil {
return nil, foundhint, err
}
if hint == nil {
return nil, foundhint, nil
}
foundhint = true
link, err := e.GetRemoteProofChainLink(m, uid, sigid)
if err != nil {
return nil, foundhint, err
}
pc, err := libkb.MakeProofChecker(m, m.G().GetProofServices(), link)
if err != nil {
return nil, foundhint, err
}
// Beyond this point, external requests will occur, and rate limiting is used
ptype := link.GetProofType()
if tickers[ptype] != nil {
m.Info("Waiting for ticker: %v (%v)", keybase1.ProofTypeRevMap[ptype], ptype)
<-tickers[ptype].C
}
pvlSource := m.G().GetPvlSource()
if pvlSource == nil {
return nil, foundhint, fmt.Errorf("no pvl source for proof verification")
}
pvlU, err := pvlSource.GetLatestEntry(m)
if err != nil {
return nil, foundhint, fmt.Errorf("error getting pvl: %s", err)
}
if _, perr := pc.CheckStatus(m, *hint, libkb.ProofCheckerModeActive, pvlU); perr != nil {
return perr, foundhint, nil
}
return nil, foundhint, nil
}
// GetSigHint gets the SigHint. This can return (nil, nil) if nothing goes wrong but there is no hint.
func (e *ScanProofsEngine) GetSigHint(m libkb.MetaContext, uid keybase1.UID, sigid keybase1.SigID) (*libkb.SigHint, error) {
sighints, err := libkb.LoadAndRefreshSigHints(m, uid)
if err != nil {
return nil, err
}
sighint := sighints.Lookup(sigid)
if sighint == nil {
return nil, nil
}
return sighint, nil
}
func (e *ScanProofsEngine) GetRemoteProofChainLink(m libkb.MetaContext, uid keybase1.UID, sigid keybase1.SigID) (libkb.RemoteProofChainLink, error) {
user, err := libkb.LoadUser(libkb.NewLoadUserArgWithMetaContext(m).WithUID(uid))
if err != nil {
return nil, fmt.Errorf("Error loading user: %v", err)
}
link := user.LinkFromSigID(sigid)
if link == nil {
return nil, fmt.Errorf("Could not find link from sigid")
}
tlink, w := libkb.NewTypedChainLink(link)
if w != nil {
return nil, fmt.Errorf("Could not get typed chain link: %v", w.Warning())
}
switch vlink := tlink.(type) {
case libkb.RemoteProofChainLink:
return vlink, nil
default:
return nil, fmt.Errorf("Link is not a RemoteProofChainLink: %v", tlink)
}
}
func (e *ScanProofsEngine) ParseIndices(indices string) (start int, end int, reterr error) {
wrap := func(format string, arg ...interface{}) error {
f2 := fmt.Sprintf("Invalid indices: %s", format)
return fmt.Errorf(f2, arg...)
}
ss := strings.Split(strings.TrimSpace(indices), ":")
if len(ss) != 2 {
return start, end, wrap("must be like start:end")
}
var err error
start, err = strconv.Atoi(ss[0])
if err != nil {
return start, end, wrap("could not convert start: %v", err)
}
end, err = strconv.Atoi(ss[1])
if err != nil {
return start, end, wrap("could not convert end: %v", err)
}
if end <= start {
return start, end, wrap("%v <= %v", end, start)
}
reterr = nil
return
}
// LoadScanProofsIgnore loads an ignore file and returns the list of proofids to ignore.
func LoadScanProofsIgnore(filepath string) ([]string, error) {
f, err := os.Open(filepath)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanLines)
var ignored []string
for scanner.Scan() {
x := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(x, "//") {
continue
}
ignored = append(ignored, x)
}
return ignored, nil
}