revocation.go 17.6 KB
Newer Older
1
2
3
4
5
6
7
package irma

import (
	"fmt"
	"time"

	"github.com/go-errors/errors"
8
9
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
10
	"github.com/privacybydesign/gabi/big"
11
	"github.com/privacybydesign/gabi/revocation"
12
	"github.com/privacybydesign/gabi/signed"
13
14
)

15
type (
Sietse Ringers's avatar
Sietse Ringers committed
16
17
18
	// RevocationStorage stores and retrieves revocation-related data from and to a SQL database,
	// and offers a revocation API for all other irmago code, including a Revoke() method that
	// revokes an earlier issued credential.
19
20
21
22
23
24
25
26
27
	RevocationStorage struct {
		conf     *Configuration
		db       revStorage
		memdb    memRevStorage
		sqlMode  bool
		settings map[CredentialTypeIdentifier]*RevocationSetting

		Keys   RevocationKeys
		client RevocationClient
28
29
	}

Sietse Ringers's avatar
Sietse Ringers committed
30
	// RevocationClient offers an HTTP client to the revocation server endpoints.
31
32
33
34
	RevocationClient struct {
		Conf *Configuration
	}

Sietse Ringers's avatar
Sietse Ringers committed
35
36
	// RevocationKeys contains helper functions for retrieving revocation private and public keys
	// from an irma.Configuration instance.
37
38
39
40
	RevocationKeys struct {
		Conf *Configuration
	}

Sietse Ringers's avatar
Sietse Ringers committed
41
	// RevocationSetting contains revocation settings for a given credential type.
42
	RevocationSetting struct {
43
44
45
		Mode                     RevocationMode `json:"mode"`
		PostURLs                 []string       `json:"post_urls" mapstructure:"post_urls"`
		MaxNonrevocationDuration uint           `json:"max_nonrev_duration" mapstructure:"max_nonrev_duration"` // in seconds, min 30
46
47
48
49
50

		// set to now whenever a new revocation record is received, or when the RA indicates
		// there are no new records. Thus it specifies up to what time our nonrevocation
		// guarantees lasts.
		updated time.Time
51
52
	}

Sietse Ringers's avatar
Sietse Ringers committed
53
54
	// RevocationMode specifies for a given credential type what revocation operations are
	// supported, and how the associated data is stored (SQL or memory).
55
	RevocationMode string
56

Sietse Ringers's avatar
Sietse Ringers committed
57
58
59
	// RevocationRecord contains a signed AccumulatorUpdate and associated information and is used
	// by clients, issuers and verifiers to update their revocation state, so that they can create
	// and verify nonrevocation proofs and witnesses.
60
61
	RevocationRecord struct {
		revocation.Record `gorm:"embedded"`
62
		PublicKeyIndex    uint
63
		CredType          CredentialTypeIdentifier `gorm:"primary_key"`
64
65
66
67
68
69
70
71
72
	}

	TimeRecord struct {
		Index      uint64
		Start, End int64
	}

	// IssuanceRecord contains information generated during issuance, needed for later revocation.
	IssuanceRecord struct {
73
74
		CredType   CredentialTypeIdentifier `gorm:"primary_key"`
		Key        string                   `gorm:"primary_key"`
75
76
77
78
79
		Attr       *big.Int
		Issued     int64
		ValidUntil int64
		RevokedAt  int64 // 0 if not currently revoked
	}
80
)
81

82
const (
Sietse Ringers's avatar
Sietse Ringers committed
83
84
	// RevocationModeRequestor is the default revocation mode in which only RevocationRecord instances
	// are consumed for issuance or verification. Uses an in-memory store.
85
	RevocationModeRequestor RevocationMode = ""
Sietse Ringers's avatar
Sietse Ringers committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104

	// RevocationModeProxy indicates that this server
	// (1) allows fetching of RevocationRecord instances from its database,
	// (2) relays all RevocationRecord instances it receives to the URLs configured in the containing
	// RevocationSetting struct.
	// Requires a SQL server to store and retrieve RevocationRecord instances from.
	RevocationModeProxy RevocationMode = "proxy"

	// RevocationModeServer indicates that this is the revocation server for a credential type,
	// to which the credential type's RevocationServer URL should point.
	// IssuanceRecord instances are sent to this server, as well as revocation commands, through
	// revocation sessions or through the RevocationStorage.Revoke() method.
	// Requires a SQL server to store and retrieve all records from and requires the issuer's
	// private key to be accessible, in order to revoke and to sign new revocation records.
	RevocationModeServer RevocationMode = "server"

	// revocationUpdateCount specifies how many revocation records are attached to session requests
	// for the client to update its revocation state.
	revocationUpdateCount = 5
105

106
107
108
	// revocationMaxAccumulatorAge is the default maximum in seconds for the 'accumulator age',
	// which we define to be the amount of time since the last confirmation from the RA that the
	// latest accumulator that we know is still the latest one: clients should prove nonrevocation
109
	// against a 'younger' accumulator.
110
	revocationMaxAccumulatorAge uint = 5 * 60
111
112
)

113
// Revocation record methods
114

Sietse Ringers's avatar
Sietse Ringers committed
115
116
117
// EnableRevocation creates an initial accumulator for a given credential type. This function is the
// only way to create such an initial accumulator and it must be called before anyone can use
// revocation for this credential type. Requires the issuer private key.
118
func (rs *RevocationStorage) EnableRevocation(typ CredentialTypeIdentifier, sk *revocation.PrivateKey) error {
119
120
121
122
123
124
125
126
	hasRecords, err := rs.db.HasRecords(typ, (*RevocationRecord)(nil))
	if err != nil {
		return err
	}
	if hasRecords {
		return errors.New("revocation record table not empty")
	}

127
128
129
130
	msg, acc, err := revocation.NewAccumulator(sk)
	if err != nil {
		return err
	}
131
132
	r := &RevocationRecord{
		Record: revocation.Record{
133
134
135
			Message:    msg,
			StartIndex: acc.Index,
			EndIndex:   acc.Index,
136
		},
137
138
		PublicKeyIndex: sk.Counter,
		CredType:       typ,
139
140
141
	}

	if err = rs.AddRevocationRecord(r); err != nil {
142
143
144
145
146
		return err
	}
	return nil
}

Sietse Ringers's avatar
Sietse Ringers committed
147
148
149
150
151
152
153
154
155
156
157
// RevocationEnabled returns whether or not revocation is enabled for the given credential type,
// by checking if any revocation record exists in the database.
func (rs *RevocationStorage) RevocationEnabled(typ CredentialTypeIdentifier) (bool, error) {
	if rs.sqlMode {
		return rs.db.HasRecords(typ, (*RevocationRecord)(nil))
	} else {
		return rs.memdb.HasRecords(typ), nil
	}
}

// RevocationRecords returns all records that a client requires to update its revocation state if it is currently
158
159
// at the specified index, that is, all records whose end index is greater than or equal to
// the specified index.
160
161
162
func (rs *RevocationStorage) RevocationRecords(typ CredentialTypeIdentifier, index uint64) ([]*RevocationRecord, error) {
	var records []*RevocationRecord
	return records, rs.db.From(typ, "end_index", index, &records)
163
164
}

165
166
167
168
169
170
171
172
func (rs *RevocationStorage) LatestRevocationRecords(typ CredentialTypeIdentifier, count uint64) ([]*RevocationRecord, error) {
	var records []*RevocationRecord
	if rs.sqlMode {
		if err := rs.db.Latest(typ, "end_index", count, &records); err != nil {
			return nil, err
		}
	} else {
		rs.memdb.Latest(typ, count, &records)
173
	}
174
175
	if len(records) == 0 {
		return nil, gorm.ErrRecordNotFound
176
	}
177
	return records, nil
178
179
}

180
func (rs *RevocationStorage) AddRevocationRecords(records []*RevocationRecord) error {
181
182
	var err error
	for _, r := range records {
183
		if err = rs.addRevocationRecord(rs.db, r, false); err != nil {
184
185
186
			return err
		}
	}
187
188
189
190
191
192

	if len(records) > 0 {
		// POST record to listeners, if any, asynchroniously
		go rs.client.PostRevocationRecords(rs.getSettings(records[0].CredType).PostURLs, records)
	}

193
194
195
	return nil
}

196
func (rs *RevocationStorage) AddRevocationRecord(record *RevocationRecord) error {
197
	return rs.addRevocationRecord(rs.db, record, true)
198
}
199

200
func (rs *RevocationStorage) addRevocationRecord(tx revStorage, record *RevocationRecord, post bool) error {
201
202
	// Unmarshal and verify the record against the appropriate public key
	pk, err := rs.Keys.PublicKey(record.CredType.IssuerIdentifier(), record.PublicKeyIndex)
203
204
205
	if err != nil {
		return err
	}
206
	_, err = record.UnmarshalVerify(pk)
207
	if err != nil {
208
209
210
		return err
	}

211
212
213
214
	// Save record
	if rs.sqlMode {
		if err = tx.Insert(record); err != nil {
			return err
215
		}
216
217
	} else {
		rs.memdb.Insert(record)
218
219
	}

220
221
	s := rs.getSettings(record.CredType)
	s.updated = time.Now()
222
223
224
225
	if post {
		// POST record to listeners, if any, asynchroniously
		go rs.client.PostRevocationRecords(s.PostURLs, []*RevocationRecord{record})
	}
226
227
228

	return nil
}
229

230
231
232
233
// Issuance records

func (rs *RevocationStorage) IssuanceRecordExists(typ CredentialTypeIdentifier, key []byte) (bool, error) {
	return rs.db.Exists(typ, "key", key, &IssuanceRecord{})
234
235
}

236
237
func (rs *RevocationStorage) AddIssuanceRecord(r *IssuanceRecord) error {
	return rs.db.Insert(r)
238
239
}

240
241
242
243
244
func (rs *RevocationStorage) IssuanceRecord(typ CredentialTypeIdentifier, key []byte) (*IssuanceRecord, error) {
	var r IssuanceRecord
	err := rs.db.Get(typ, "key", key, &r)
	if err != nil {
		return nil, err
245
	}
246
247
	return &r, nil
}
248

249
250
// Revocation methods

Sietse Ringers's avatar
Sietse Ringers committed
251
252
// Revoke revokes the credential specified by key if found within the current database,
// by updating its revocation time to now, removing its revocation attribute from the current accumulator,
253
// and updating the revocation database on disk.
254
func (rs *RevocationStorage) Revoke(typ CredentialTypeIdentifier, key string, sk *revocation.PrivateKey) error {
Sietse Ringers's avatar
Sietse Ringers committed
255
256
	if rs.getSettings(typ).Mode != RevocationModeServer {
		return errors.Errorf("cannot revoke %s", typ)
257
	}
258

259
260
261
262
263
264
265
266
267
268
	return rs.db.Transaction(func(tx revStorage) error {
		var err error
		cr := IssuanceRecord{}
		if err = tx.Get(typ, "key", key, &cr); err != nil {
			return err
		}
		cr.RevokedAt = time.Now().UnixNano()
		if err = tx.Save(&cr); err != nil {
			return err
		}
269
		return rs.revokeAttr(tx, typ, sk, cr.Attr)
270
271
272
	})
}

273
274
275
276
277
278
279
280
281
282
func (rs *RevocationStorage) revokeAttr(tx revStorage, typ CredentialTypeIdentifier, sk *revocation.PrivateKey, e *big.Int) error {
	cur, err := rs.currentAccumulator(tx, typ)
	if err != nil {
		return err
	}
	if cur == nil {
		return errors.Errorf("cannot revoke for type %s, not enabled yet", typ)
	}

	newAcc, err := cur.Remove(sk, e)
283
284
285
	if err != nil {
		return err
	}
286
	update := &revocation.AccumulatorUpdate{
287
288
289
290
291
292
293
294
295
		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
	}
296
297
	record := &RevocationRecord{
		Record: revocation.Record{
298
299
300
			StartIndex: newAcc.Index,
			EndIndex:   newAcc.Index,
			Message:    updateMsg,
301
		},
302
303
		PublicKeyIndex: sk.Counter,
		CredType:       typ,
304
	}
305
	if err = rs.addRevocationRecord(tx, record, true); err != nil {
306
307
308
309
310
		return err
	}
	return nil
}

311
// Accumulator methods
312

313
314
func (rs *RevocationStorage) CurrentAccumulator(typ CredentialTypeIdentifier) (*revocation.Accumulator, error) {
	return rs.currentAccumulator(rs.db, typ)
315
316
}

317
318
func (rs *RevocationStorage) currentAccumulator(tx revStorage, typ CredentialTypeIdentifier) (rec *revocation.Accumulator, err error) {
	record := &RevocationRecord{}
319

320
321
322
323
324
	if rs.sqlMode {
		if err := tx.Last(typ, record); err != nil {
			if gorm.IsRecordNotFoundError(err) {
				return nil, nil
			}
325
326
			return nil, err
		}
327
328
329
330
331
332
333
	} else {
		var r []*RevocationRecord
		rs.memdb.Latest(typ, 1, &r)
		if len(r) == 0 {
			return nil, nil
		}
		record = r[0]
334
335
	}

336
	pk, err := rs.Keys.PublicKey(typ.IssuerIdentifier(), record.PublicKeyIndex)
337
338
339
	if err != nil {
		return nil, err
	}
340
341
	var u revocation.AccumulatorUpdate
	if err = signed.UnmarshalVerify(pk.ECDSA, record.Message, &u); err != nil {
342
343
		return nil, err
	}
344
	return &u.Accumulator, nil
345
346
}

347
348
349
350
// Methods to update from remote revocation server

func (rs *RevocationStorage) UpdateDB(typ CredentialTypeIdentifier) error {
	records, err := rs.client.FetchLatestRevocationRecords(typ, revocationUpdateCount)
351
	if err != nil {
352
		return err
353
	}
354
355
356
357
358
359
360
361

	if err = rs.AddRevocationRecords(records); err != nil {
		return err
	}

	// bump updated even if no new records were added
	rs.getSettings(typ).updated = time.Now()
	return nil
362
363
}

Sietse Ringers's avatar
Sietse Ringers committed
364
func (rs *RevocationStorage) UpdateIfOld(typ CredentialTypeIdentifier) error {
365
	settings := rs.getSettings(typ)
366
	// update 10 seconds before the maximum, to stay below it
367
	if settings.updated.Before(time.Now().Add(time.Duration(-settings.MaxNonrevocationDuration+10) * time.Second)) {
368
		if err := rs.UpdateDB(typ); err != nil {
369
370
371
372
373
374
			return err
		}
	}
	return nil
}

375
376
377
378
379
380
381
382
// SaveIssuanceRecord either stores the issuance record locally, if we are the revocation server of
// the crecential type, or it signs and sends it to the remote revocation server.
func (rs *RevocationStorage) SaveIssuanceRecord(typ CredentialTypeIdentifier, rec *IssuanceRecord) error {
	// TODO store locally if appropriate?

	// Just store it if we are the revocation server for this credential type
	if rs.getSettings(typ).Mode == RevocationModeServer {
		return rs.AddIssuanceRecord(rec)
383
384
	}

385
386
387
388
389
390
391
392
393
	// We have to send it, sign it first
	credtype := rs.conf.CredentialTypes[typ]
	if credtype == nil {
		return errors.New("unknown credential type")
	}
	if credtype.RevocationServer == "" {
		return errors.New("credential type has no revocation server")
	}
	sk, err := rs.Keys.PrivateKey(typ.IssuerIdentifier())
394
395
396
	if err != nil {
		return err
	}
397
	message, err := signed.MarshalSign(sk.ECDSA, rec)
398
399
400
	if err != nil {
		return err
	}
401
402

	return rs.client.PostIssuanceRecord(typ, sk.Counter, message)
403
404
}

405
406
407
// Misscelaneous methods

func (rs *RevocationStorage) Load(debug bool, connstr string, settings map[CredentialTypeIdentifier]*RevocationSetting) error {
408
409
410
411
412
413
414
415
	var t *CredentialTypeIdentifier
	for typ, s := range settings {
		switch s.Mode {
		case RevocationModeServer, RevocationModeProxy:
			t = &typ
		default:
			return errors.Errorf("invalid revocation mode '%s' for %s (supported: %s, %s)",
				s.Mode, typ, RevocationModeServer, RevocationModeProxy)
416
		}
417
	}
418
419
420
	if t != nil && connstr == "" {
		return errors.Errorf("revocation mode for %s requires SQL database but no connection string given", *t)
	}
421
422
423
424
425
426
427
428

	if connstr == "" {
		Logger.Trace("Using memory revocation database")
		rs.memdb = newMemStorage()
		rs.sqlMode = false
	} else {
		Logger.Trace("Connecting to revocation SQL database")
		db, err := newSqlStorage(debug, connstr)
429
		if err != nil {
430
			return err
431
		}
432
433
		rs.db = db
		rs.sqlMode = true
434
	}
435
436
437
438
439
	if settings != nil {
		rs.settings = settings
	} else {
		rs.settings = map[CredentialTypeIdentifier]*RevocationSetting{}
	}
440
441
442
443
444
445
	for id, settings := range rs.settings {
		if settings.MaxNonrevocationDuration != 0 && settings.MaxNonrevocationDuration < 30 {
			return errors.Errorf("max_nonrev_duration setting for %s must be at least 30 seconds, was %d",
				id, settings.MaxNonrevocationDuration)
		}
	}
446
447
448
	rs.client = RevocationClient{Conf: rs.conf}
	rs.Keys = RevocationKeys{Conf: rs.conf}
	return nil
449
450
}

451
452
453
func (rs *RevocationStorage) Close() error {
	if rs.db != nil {
		return rs.db.Close()
454
455
456
457
	}
	return nil
}

458
459
460
461
462
463
// SetRevocationRecords retrieves the latest revocation records from the database, and attaches
// them to the request, for each credential type for which a nonrevocation proof is requested in
// b.Revocation.
func (rs *RevocationStorage) SetRevocationRecords(b *BaseRequest) error {
	if len(b.Revocation) == 0 {
		return nil
464
	}
465
466
467
	var err error
	b.RevocationUpdates = make(map[CredentialTypeIdentifier][]*RevocationRecord, len(b.Revocation))
	for _, credid := range b.Revocation {
Sietse Ringers's avatar
Sietse Ringers committed
468
		if err = rs.UpdateIfOld(credid); err != nil {
469
470
471
472
473
474
475
476
477
478
479
480
			updated := rs.getSettings(credid).updated
			if !updated.IsZero() {
				Logger.Warnf("failed to fetch revocation updates for %s, nonrevocation is guaranteed only until %s ago:",
					credid, time.Now().Sub(updated).String())
				Logger.Warn(err)
			} else {
				Logger.Errorf("revocation is disabled for %s: failed to fetch revocation updates and none are known locally", credid)
				Logger.Warn(err)
				// We can offer no nonrevocation guarantees at all while the requestor explicitly
				// asked for it; fail the session by returning an error
				return err
			}
481
482
483
484
485
		}
		b.RevocationUpdates[credid], err = rs.LatestRevocationRecords(credid, revocationUpdateCount)
		if err != nil {
			return err
		}
486
	}
487
488
489
490
491
492
	return nil
}

func (rs *RevocationStorage) getSettings(typ CredentialTypeIdentifier) *RevocationSetting {
	if rs.settings[typ] == nil {
		rs.settings[typ] = &RevocationSetting{}
493
	}
494
495
496
497
498
	s := rs.settings[typ]
	if s.MaxNonrevocationDuration == 0 {
		s.MaxNonrevocationDuration = revocationMaxAccumulatorAge
	}
	return s
499
500
}

501
func (RevocationClient) PostRevocationRecords(urls []string, records []*RevocationRecord) {
502
	transport := NewHTTPTransport("")
503
504
	for _, url := range urls {
		if err := transport.Post(url+"/-/revocation/records", nil, &records); err != nil {
505
506
			Logger.Warn("error sending revocation update", err)
		}
507
	}
508
509
510
511
512
513
514
515
516
517
518
519
520
}

func (client RevocationClient) PostIssuanceRecord(typ CredentialTypeIdentifier, counter uint, message signed.Message) error {
	return NewHTTPTransport(client.Conf.CredentialTypes[typ].RevocationServer).Post(
		fmt.Sprintf("-/revocation/issuancerecord/%s/%d", typ, counter), nil, []byte(message),
	)
}

// FetchRevocationRecords gets revocation update messages from the revocation server, of the specified index and greater.
func (client RevocationClient) FetchRevocationRecords(typ CredentialTypeIdentifier, index uint64) ([]*RevocationRecord, error) {
	var records []*RevocationRecord
	err := NewHTTPTransport(client.Conf.CredentialTypes[typ].RevocationServer).
		Get(fmt.Sprintf("-/revocation/records/%s/%d", typ, index), &records)
521
	if err != nil {
522
		return nil, err
523
	}
524
525
	return records, nil
}
526

527
528
529
530
func (client RevocationClient) FetchLatestRevocationRecords(typ CredentialTypeIdentifier, count uint64) ([]*RevocationRecord, error) {
	var records []*RevocationRecord
	err := NewHTTPTransport(client.Conf.CredentialTypes[typ].RevocationServer).
		Get(fmt.Sprintf("-/revocation/latestrecords/%s/%d", typ, count), &records)
531
	if err != nil {
532
		return nil, err
533
	}
534
	return records, nil
535
536
}

537
538
func (rs RevocationKeys) PrivateKey(issid IssuerIdentifier) (*revocation.PrivateKey, error) {
	sk, err := rs.Conf.PrivateKey(issid)
539
	if err != nil {
540
		return nil, err
541
542
	}
	if sk == nil {
543
		return nil, errors.Errorf("unknown private key: %s", issid)
544
	}
545
	revsk, err := sk.RevocationKey()
546
	if err != nil {
547
		return nil, err
548
	}
549
550
	return revsk, nil
}
551

552
553
func (rs RevocationKeys) PublicKey(issid IssuerIdentifier, counter uint) (*revocation.PublicKey, error) {
	pk, err := rs.Conf.PublicKey(issid, int(counter))
554
	if err != nil {
555
		return nil, err
556
	}
557
558
	if pk == nil {
		return nil, errors.Errorf("unknown public key: %s-%d", issid, counter)
559
	}
560
561
562
	revpk, err := pk.RevocationKey()
	if err != nil {
		return nil, err
563
	}
564
	return revpk, nil
565
}