revocation.go 13.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
package irma

import (
	"fmt"
	"path/filepath"
	"time"

	"github.com/go-errors/errors"
	"github.com/hashicorp/go-multierror"
10
	"github.com/privacybydesign/gabi/big"
11
	"github.com/privacybydesign/gabi/revocation"
12
	"github.com/privacybydesign/gabi/signed"
13
14
	"github.com/timshannon/bolthold"
	bolt "go.etcd.io/bbolt"
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
type (
	// Keystore provides support for revocation public key rollover.
	Keystore interface {
		// PublicKey either returns the specified, non-nil public key or an error
		PublicKey(counter uint) (*revocation.PublicKey, error)
	}

	// DB is a bolthold database storing revocation state for a particular accumulator
	// (Record instances, and IssuanceRecord instances if used by an issuer).
	DB struct {
		Current  revocation.Accumulator
		Updated  time.Time
		onChange []func(*Record)
		bolt     *bolthold.Store
		keystore Keystore
	}

	RevocationStorage struct {
		dbs  map[CredentialTypeIdentifier]*DB
		conf *Configuration
	}

	// Record contains a signed AccumulatorUpdate and associated information.
	Record struct {
		StartIndex     uint64
		EndIndex       uint64
		PublicKeyIndex uint
		Message        signed.Message // signed revocation.AccumulatorUpdate
	}

	TimeRecord struct {
		Index      uint64
		Start, End int64
	}

	// IssuanceRecord contains information generated during issuance, needed for later revocation.
	IssuanceRecord struct {
		Key        string
		Attr       *big.Int
		Issued     int64
		ValidUntil int64
		RevokedAt  int64 // 0 if not currently revoked
	}

	currentRecord struct {
		Index uint64
	}
)

const boltCurrentIndexKey = "currentIndex"

func (conf *Configuration) RevocationKeystore(issuerid IssuerIdentifier) Keystore {
69
70
71
	return &issuerKeystore{issid: issuerid, conf: conf}
}

72
// issuerKeystore implements Keystore.
73
74
75
76
77
type issuerKeystore struct {
	issid IssuerIdentifier
	conf  *Configuration
}

78
var _ Keystore = (*issuerKeystore)(nil)
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

func (ks *issuerKeystore) PublicKey(counter uint) (*revocation.PublicKey, error) {
	pk, err := ks.conf.PublicKey(ks.issid, int(counter))
	if err != nil {
		return nil, err
	}
	if pk == nil {
		return nil, errors.Errorf("public key %d of issuer %s not found", counter, ks.issid)
	}
	if !pk.RevocationSupported() {
		return nil, errors.Errorf("public key %d of issuer %s does not support revocation", counter, ks.issid)
	}
	rpk, err := pk.RevocationKey()
	if err != nil {
		return nil, err
	}
	return rpk, nil
}

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
func (rdb *DB) EnableRevocation(sk *revocation.PrivateKey) error {
	msg, acc, err := revocation.NewAccumulator(sk)
	if err != nil {
		return err
	}
	if err = rdb.Add(msg, sk.Counter); err != nil {
		return err
	}
	rdb.Current = acc
	return nil
}

// Revoke revokes the credential specified specified by key if found within the current database,
// by updating its revocation time to now, adding its revocation attribute to the current accumulator,
// and updating the revocation database on disk.
func (rdb *DB) Revoke(sk *revocation.PrivateKey, key []byte) error {
	return rdb.bolt.Bolt().Update(func(tx *bolt.Tx) error {
		var err error
		cr := IssuanceRecord{}
		if err = rdb.bolt.TxGet(tx, key, &cr); err != nil {
			return err
		}
		cr.RevokedAt = time.Now().UnixNano()
		if err = rdb.bolt.TxUpdate(tx, key, &cr); err != nil {
			return err
		}
		return rdb.revokeAttr(sk, cr.Attr, tx)
	})
}

// Get returns all records that a client requires to update its revocation state if it is currently
// at the specified index, that is, all records whose end index is greater than or equal to
// the specified index.
func (rdb *DB) RevocationRecords(index int) ([]*Record, error) {
	var records []*Record
	if err := rdb.bolt.Find(&records, bolthold.Where(bolthold.Key).Ge(uint64(index))); err != nil {
		return nil, err
	}
	return records, nil
}

func (rdb *DB) LatestRecords(count int) ([]*Record, error) {
	c := int(rdb.Current.Index) - count + 1
	if c < 0 {
		c = 0
	}
	return rdb.RevocationRecords(c)
}

func (rdb *DB) IssuanceRecordExists(key []byte) (bool, error) {
	_, err := rdb.IssuanceRecord(key)
	switch err {
	case nil:
		return true, nil
	case bolthold.ErrNotFound:
		return false, nil
	default:
		return false, err
	}
}

func (rdb *DB) AddIssuanceRecord(r *IssuanceRecord) error {
	return rdb.bolt.Insert([]byte(r.Key), r)
}

func (rdb *DB) IssuanceRecord(key []byte) (*IssuanceRecord, error) {
	r := &IssuanceRecord{}
	if err := rdb.bolt.Get(key, r); err != nil {
		return nil, err
	}
	return r, nil
}

func (rdb *DB) AddRecords(records []*Record) error {
	var err error
	for _, r := range records {
		if err = rdb.Add(r.Message, r.PublicKeyIndex); err != nil {
			return err
		}
	}
	rdb.Updated = time.Now() // TODO update this in add()?
	return nil
}

func (rdb *DB) Add(updateMsg signed.Message, counter uint) error {
	var err error
	var update revocation.AccumulatorUpdate

	pk, err := rdb.keystore.PublicKey(counter)
	if err != nil {
		return err
	}

	if err = signed.UnmarshalVerify(pk.ECDSA, updateMsg, &update); err != nil {
		return err
	}

	return rdb.bolt.Bolt().Update(func(tx *bolt.Tx) error {
		return rdb.add(update, updateMsg, counter, tx)
	})
}

func (rdb *DB) add(update revocation.AccumulatorUpdate, updateMsg signed.Message, pkCounter uint, tx *bolt.Tx) error {
	var err error
	record := &Record{
		StartIndex:     update.StartIndex,
		EndIndex:       update.Accumulator.Index,
		PublicKeyIndex: pkCounter,
		Message:        updateMsg,
	}
	if err = rdb.bolt.TxInsert(tx, update.Accumulator.Index, record); err != nil {
		return err
	}

	if update.Accumulator.Index != 0 {
		var tr TimeRecord
		if err = rdb.bolt.TxGet(tx, update.Accumulator.Index-1, &tr); err == nil {
			tr.End = time.Now().UnixNano()
			if err = rdb.bolt.TxUpdate(tx, update.Accumulator.Index-1, &tr); err != nil {
				return err
			}
		}
	}
	if err = rdb.bolt.TxInsert(tx, update.Accumulator.Index, &TimeRecord{
		Index: update.Accumulator.Index,
		Start: time.Now().UnixNano(),
	}); err != nil {
		return err
	}

	if err = rdb.bolt.TxUpsert(tx, boltCurrentIndexKey, &currentRecord{update.Accumulator.Index}); err != nil {
		return err
	}

	for _, f := range rdb.onChange {
		f(record)
	}

	rdb.Current = update.Accumulator
	return nil
}

func (rdb *DB) Enabled() bool {
	var currentIndex currentRecord
	err := rdb.bolt.Get(boltCurrentIndexKey, &currentIndex)
	return err == nil
}

func (rdb *DB) loadCurrent() error {
	var currentIndex currentRecord
	if err := rdb.bolt.Get(boltCurrentIndexKey, &currentIndex); err == bolthold.ErrNotFound {
		return errors.New("revocation database not initialized")
	} else if err != nil {
		return err
	}

	var record Record
	if err := rdb.bolt.Get(currentIndex.Index, &record); err != nil {
		return err
	}
	pk, err := rdb.keystore.PublicKey(record.PublicKeyIndex)
	if err != nil {
		return err
	}
	var u revocation.AccumulatorUpdate
	if err = signed.UnmarshalVerify(pk.ECDSA, record.Message, &u); err != nil {
		return err
	}
	rdb.Current = u.Accumulator
	return nil
}

func (rdb *DB) RevokeAttr(sk *revocation.PrivateKey, e *big.Int) error {
	return rdb.bolt.Bolt().Update(func(tx *bolt.Tx) error {
		return rdb.revokeAttr(sk, e, tx)
	})
}

func (rdb *DB) revokeAttr(sk *revocation.PrivateKey, e *big.Int, tx *bolt.Tx) error {
	// don't update rdb.Current until after all possible errors are handled
	newAcc, err := rdb.Current.Remove(sk, e)
	if err != nil {
		return err
	}
	update := revocation.AccumulatorUpdate{
		Accumulator: *newAcc,
		StartIndex:  newAcc.Index,
		Revoked:     []*big.Int{e},
		Time:        time.Now().UnixNano(),
	}
	updateMsg, err := signed.MarshalSign(sk.ECDSA, update)
	if err != nil {
		return err
	}
	if err = rdb.add(update, updateMsg, sk.Counter, tx); err != nil {
		return err
	}
	rdb.Current = *newAcc
	return nil
}

func (rdb *DB) Close() error {
	rdb.onChange = nil
	if rdb.bolt != nil {
		return rdb.bolt.Close()
	}
	return nil
}

func (rdb *DB) OnChange(handler func(*Record)) {
	rdb.onChange = append(rdb.onChange, handler)
}

func (r *Record) UnmarshalVerify(keystore Keystore) (*revocation.AccumulatorUpdate, error) {
	pk, err := keystore.PublicKey(r.PublicKeyIndex)
	if err != nil {
		return nil, err
	}
	msg := &revocation.AccumulatorUpdate{}
	if err := signed.UnmarshalVerify(pk.ECDSA, r.Message, msg); err != nil {
		return nil, err
	}
	if (r.StartIndex != msg.StartIndex) ||
		(r.EndIndex > 0 && r.EndIndex != msg.StartIndex+uint64(len(msg.Revoked))-1) {
		return nil, errors.New("record has invalid start or end index")
	}
	return msg, nil
}

func (rs *RevocationStorage) LoadDB(credid CredentialTypeIdentifier) (*DB, error) {
	path := filepath.Join(rs.conf.RevocationPath, credid.String())
	keystore := rs.conf.RevocationKeystore(credid.IssuerIdentifier())

	b, err := bolthold.Open(path, 0600, &bolthold.Options{Options: &bolt.Options{Timeout: 1 * time.Second}})
	if err != nil {
		return nil, err
	}
	db := &DB{
		bolt:     b,
		keystore: keystore,
	}
	if db.Enabled() {
		if err = db.loadCurrent(); err != nil {
			_ = db.Close()
			return nil, err
		}
	}
	return db, nil
}

func (rs *RevocationStorage) PrivateKey(issid IssuerIdentifier) (*revocation.PrivateKey, error) {
	pk, err := rs.conf.PrivateKey(issid)
	if err != nil {
		return nil, err
	}
	if pk == nil {
		return nil, errors.Errorf("unknown public key: %s", issid)
	}
	revpk, err := pk.RevocationKey()
	if err != nil {
		return nil, err
	}
	return revpk, nil
}

func (rs *RevocationStorage) PublicKey(issid IssuerIdentifier, counter uint) (*revocation.PublicKey, error) {
	pk, err := rs.conf.PublicKey(issid, int(counter))
	if err != nil {
		return nil, err
	}
	if pk == nil {
		return nil, errors.Errorf("unknown public key: %s-%d", issid, counter)
	}
	revpk, err := pk.RevocationKey()
	if err != nil {
		return nil, err
	}
	return revpk, nil
}

func (rs *RevocationStorage) UpdateWitness(w *revocation.Witness, msgs []*Record, issid IssuerIdentifier) (bool, error) {
	var err error
	var pk *revocation.PublicKey
	oldindex := w.Index
	for _, msg := range msgs {
		if pk, err = rs.PublicKey(issid, msg.PublicKeyIndex); err != nil {
			return false, err
		}
		if err = w.Update(pk, msg.Message); err != nil {
			return false, err
		}
	}
	return w.Index == oldindex, nil
}

func (rs *RevocationStorage) RevocationGetUpdates(credid CredentialTypeIdentifier, index uint64) ([]*Record, error) {
	var records []*Record
	err := NewHTTPTransport(rs.conf.CredentialTypes[credid].RevocationServer).
396
397
398
399
400
401
402
		Get(fmt.Sprintf("-/revocation/records/%s/%d", credid, index), &records)
	if err != nil {
		return nil, err
	}
	return records, nil
}

403
func (rs *RevocationStorage) RevocationUpdateAll() error {
404
	var err error
405
406
	for credid := range rs.dbs {
		if err = rs.RevocationUpdateDB(credid); err != nil {
407
408
409
410
411
412
			return err
		}
	}
	return nil
}

413
func (rs *RevocationStorage) RevocationSetRecords(b *BaseRequest) error {
414
415
416
	if len(b.Revocation) == 0 {
		return nil
	}
417
	b.RevocationUpdates = make(map[CredentialTypeIdentifier][]*Record, len(b.Revocation))
418
	for _, credid := range b.Revocation {
419
		db, err := rs.RevocationDB(credid)
420
421
422
		if err != nil {
			return err
		}
423
		if err = rs.revocationUpdateDelayed(credid, db); err != nil {
424
425
426
427
428
429
430
431
432
433
			return err
		}
		b.RevocationUpdates[credid], err = db.LatestRecords(revocationUpdateCount)
		if err != nil {
			return err
		}
	}
	return nil
}

434
435
func (rs *RevocationStorage) RevocationUpdateDB(credid CredentialTypeIdentifier) error {
	db, err := rs.RevocationDB(credid)
436
437
438
439
440
441
442
	if err != nil {
		return err
	}
	var index uint64
	if db.Enabled() {
		index = db.Current.Index + 1
	}
443
	records, err := rs.RevocationGetUpdates(credid, index)
444
445
446
447
448
449
	if err != nil {
		return err
	}
	return db.AddRecords(records)
}

450
451
func (rs *RevocationStorage) RevocationDB(credid CredentialTypeIdentifier) (*DB, error) {
	if _, known := rs.conf.CredentialTypes[credid]; !known {
452
453
		return nil, errors.New("unknown credential type")
	}
454
455
	if rs.dbs == nil {
		rs.dbs = make(map[CredentialTypeIdentifier]*DB)
456
	}
457
	if rs.dbs[credid] == nil {
458
		var err error
459
		db, err := rs.LoadDB(credid)
460
461
462
		if err != nil {
			return nil, err
		}
463
		rs.dbs[credid] = db
464
	}
465
	return rs.dbs[credid], nil
466
467
}

468
func (rs *RevocationStorage) revocationUpdateDelayed(credid CredentialTypeIdentifier, db *DB) error {
469
	if db.Updated.Before(time.Now().Add(-5 * time.Minute)) {
470
		if err := rs.RevocationUpdateDB(credid); err != nil {
471
472
473
474
475
476
			return err
		}
	}
	return nil
}

477
478
func (rs *RevocationStorage) SendRevocationIssuanceRecord(
	cred CredentialTypeIdentifier, rec *IssuanceRecord,
479
) error {
480
	credtype := rs.conf.CredentialTypes[cred]
481
482
483
484
485
486
	if credtype == nil {
		return errors.New("unknown credential type")
	}
	if credtype.RevocationServer == "" {
		return errors.New("credential type has no revocation server")
	}
487
	sk, err := rs.conf.PrivateKey(cred.IssuerIdentifier())
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
	if err != nil {
		return err
	}
	if sk == nil {
		return errors.New("private key not found")
	}
	revsk, err := sk.RevocationKey()
	if err != nil {
		return err
	}

	message, err := signed.MarshalSign(revsk.ECDSA, rec)
	if err != nil {
		return err
	}
	return NewHTTPTransport(credtype.RevocationServer).Post(
		fmt.Sprintf("-/revocation/issuancerecord/%s/%d", cred, sk.Counter), nil, []byte(message),
	)
}

508
509
func (rs *RevocationStorage) Revoke(credid CredentialTypeIdentifier, key string) error {
	sk, err := rs.conf.PrivateKey(credid.IssuerIdentifier())
510
511
512
513
514
515
516
517
518
519
520
	if err != nil {
		return err
	}
	if sk == nil {
		return errors.New("private key not found")
	}
	rsk, err := sk.RevocationKey()
	if err != nil {
		return err
	}

521
	db, err := rs.RevocationDB(credid)
522
523
524
525
526
527
	if err != nil {
		return err
	}
	return db.Revoke(rsk, []byte(key))
}

528
func (rs *RevocationStorage) Close() error {
529
530
	merr := &multierror.Error{}
	var err error
531
	for _, db := range rs.dbs {
532
533
534
535
		if err = db.Close(); err != nil {
			merr = multierror.Append(merr, err)
		}
	}
536
	rs.dbs = nil
537
538
	return merr.ErrorOrNil()
}