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

import (
	"fmt"
	"time"

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

17
type (
Sietse Ringers's avatar
Sietse Ringers committed
18 19 20
	// 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.
21 22 23 24 25 26 27 28 29
	RevocationStorage struct {
		conf     *Configuration
		db       revStorage
		memdb    memRevStorage
		sqlMode  bool
		settings map[CredentialTypeIdentifier]*RevocationSetting

		Keys   RevocationKeys
		client RevocationClient
30 31
	}

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

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

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

50 51
		// set to now whenever a new update is received, or when the RA indicates
		// there are no new updates. Thus it specifies up to what time our nonrevocation
52 53
		// guarantees lasts.
		updated time.Time
54 55
	}

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

61 62 63 64 65
// Structs corresponding to SQL table rows. All of them end in Record.
type (
	AccumulatorRecord struct {
		*revocation.SignedAccumulator `gorm:"embedded"`
		CredType                      CredentialTypeIdentifier `gorm:"primary_key"`
66 67
	}

68 69 70
	EventRecord struct {
		*revocation.Event `gorm:"embedded"`
		CredType          CredentialTypeIdentifier `gorm:"primary_key"`
71 72 73 74
	}

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

	// TODO
	TimeRecord struct {
		Index      uint64
		Start, End int64
	}
88
)
89

90
const (
Sietse Ringers's avatar
Sietse Ringers committed
91 92
	// RevocationModeRequestor is the default revocation mode in which only RevocationRecord instances
	// are consumed for issuance or verification. Uses an in-memory store.
93
	RevocationModeRequestor RevocationMode = ""
Sietse Ringers's avatar
Sietse Ringers committed
94 95

	// RevocationModeProxy indicates that this server
96 97
	// (1) allows fetching of revocation update messages from its database,
	// (2) relays all revocation updates it receives to the URLs configured in the containing
Sietse Ringers's avatar
Sietse Ringers committed
98
	// RevocationSetting struct.
99
	// Requires a SQL server to store and retrieve update messages from.
Sietse Ringers's avatar
Sietse Ringers committed
100 101
	RevocationModeProxy RevocationMode = "proxy"

102
	// RevocationModeServer indicates that this is a revocation server for a credential type.
Sietse Ringers's avatar
Sietse Ringers committed
103 104 105
	// 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
106
	// private key to be accessible, in order to revoke and to sign new revocation update messages.
107
	// In addition this mode exposes the same endpoints as RevocationModeProxy.
Sietse Ringers's avatar
Sietse Ringers committed
108 109
	RevocationModeServer RevocationMode = "server"

110
	// revocationUpdateCount specifies how many revocation events are attached to session requests
Sietse Ringers's avatar
Sietse Ringers committed
111 112
	// for the client to update its revocation state.
	revocationUpdateCount = 5
113

114 115 116
	// 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
117
	// against a 'younger' accumulator.
118
	revocationMaxAccumulatorAge uint = 5 * 60
119 120
)

Sietse Ringers's avatar
Sietse Ringers committed
121 122 123
// 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.
124
func (rs *RevocationStorage) EnableRevocation(typ CredentialTypeIdentifier, sk *revocation.PrivateKey) error {
125
	hasRecords, err := rs.db.HasRecords(typ, (*EventRecord)(nil))
126 127 128 129
	if err != nil {
		return err
	}
	if hasRecords {
130
		return errors.New("revocation event record table not empty")
131 132
	}

133
	update, err := revocation.NewAccumulator(sk)
134 135 136
	if err != nil {
		return err
	}
137

138
	if err = rs.addUpdate(rs.db, typ, update, true); err != nil {
139 140 141 142 143
		return err
	}
	return nil
}

Sietse Ringers's avatar
Sietse Ringers committed
144 145 146 147
// 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 {
148
		return rs.db.HasRecords(typ, (*EventRecord)(nil))
Sietse Ringers's avatar
Sietse Ringers committed
149 150 151 152 153
	} else {
		return rs.memdb.HasRecords(typ), nil
	}
}

154 155 156
// Revocation update message methods

// UpdateFrom returns all records that a client requires to update its revocation state if it is currently
157 158
// at the specified index, that is, all records whose end index is greater than or equal to
// the specified index.
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
func (rs *RevocationStorage) UpdateFrom(typ CredentialTypeIdentifier, index uint64) (*revocation.Update, error) {
	// Only requires SQL implementation
	var update *revocation.Update
	if err := rs.db.Transaction(func(tx revStorage) error {
		acc, _, err := rs.currentAccumulator(tx, typ)
		if err != nil {
			return err
		}
		var events []*EventRecord
		if err := tx.From(typ, "index", index, &events); err != nil {
			return err
		}
		update = rs.newUpdate(acc, events)
		return nil
	}); err != nil {
		return nil, err
	}
	return update, nil
177 178
}

179 180
func (rs *RevocationStorage) UpdateLatest(typ CredentialTypeIdentifier, count uint64) (*revocation.Update, error) {
	// TODO what should this function and UpdateFrom return when no records are found?
181
	if rs.sqlMode {
182 183 184 185 186 187 188 189 190 191 192 193 194
		var update *revocation.Update
		if err := rs.db.Transaction(func(tx revStorage) error {
			acc, _, err := rs.currentAccumulator(tx, typ)
			if err != nil {
				return err
			}
			var events []*EventRecord
			if err := tx.Latest(typ, "index", count, &events); err != nil {
				return err
			}
			update = rs.newUpdate(acc, events)
			return nil
		}); err != nil {
195 196
			return nil, err
		}
197
		return update, nil
198
	} else {
199
		return rs.memdb.Latest(typ, count), nil
200 201 202
	}
}

203 204 205 206
func (*RevocationStorage) newUpdate(acc *revocation.SignedAccumulator, events []*EventRecord) *revocation.Update {
	updates := make([]*revocation.Event, len(events))
	for i := range events {
		updates[i] = events[i].Event
207
	}
208 209 210
	return &revocation.Update{
		SignedAccumulator: acc,
		Events:            updates,
211
	}
212 213
}

214
func (rs *RevocationStorage) AddUpdate(typ CredentialTypeIdentifier, record *revocation.Update) error {
215
	return rs.addUpdate(rs.db, typ, record, false)
216
}
217

218
func (rs *RevocationStorage) addUpdate(tx revStorage, typ CredentialTypeIdentifier, update *revocation.Update, create bool) error {
219
	// Unmarshal and verify the record against the appropriate public key
220
	pk, err := rs.Keys.PublicKey(typ.IssuerIdentifier(), update.SignedAccumulator.PKIndex)
221 222 223
	if err != nil {
		return err
	}
224
	if _, _, err = update.Verify(pk, 0); err != nil {
225 226 227
		return err
	}

228 229
	// Save record
	if rs.sqlMode {
230 231 232 233 234
		save := tx.Save
		if create {
			save = tx.Insert
		}
		if err = save(&AccumulatorRecord{SignedAccumulator: update.SignedAccumulator, CredType: typ}); err != nil {
235
			return err
236
		}
237 238 239 240 241
		for _, event := range update.Events {
			if err = tx.Insert(&EventRecord{Event: event, CredType: typ}); err != nil {
				return err
			}
		}
242
	} else {
243
		rs.memdb.Insert(typ, update)
244 245
	}

246
	s := rs.getSettings(typ)
247
	s.updated = time.Now()
248 249
	// POST record to listeners, if any, asynchroniously
	go rs.client.PostUpdate(typ, s.PostURLs, update)
250 251 252

	return nil
}
253

254 255 256 257
// Issuance records

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

260 261
func (rs *RevocationStorage) AddIssuanceRecord(r *IssuanceRecord) error {
	return rs.db.Insert(r)
262 263
}

264 265 266 267 268
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
269
	}
270 271
	return &r, nil
}
272

273 274
// Revocation methods

Sietse Ringers's avatar
Sietse Ringers committed
275 276
// 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,
277
// and updating the revocation database on disk.
278
func (rs *RevocationStorage) Revoke(typ CredentialTypeIdentifier, key string, sk *revocation.PrivateKey) error {
Sietse Ringers's avatar
Sietse Ringers committed
279 280
	if rs.getSettings(typ).Mode != RevocationModeServer {
		return errors.Errorf("cannot revoke %s", typ)
281
	}
282

283 284
	return rs.db.Transaction(func(tx revStorage) error {
		var err error
285 286
		issrecord := IssuanceRecord{}
		if err = tx.Get(typ, "key", key, &issrecord); err != nil {
287 288
			return err
		}
289 290
		issrecord.RevokedAt = time.Now().UnixNano()
		if err = tx.Save(&issrecord); err != nil {
291 292
			return err
		}
293
		return rs.revokeAttr(tx, typ, sk, issrecord.Attr)
294 295 296
	})
}

297
func (rs *RevocationStorage) revokeAttr(tx revStorage, typ CredentialTypeIdentifier, sk *revocation.PrivateKey, e *big.Int) error {
298
	_, cur, err := rs.currentAccumulator(tx, typ)
299 300 301 302 303 304
	if err != nil {
		return err
	}
	if cur == nil {
		return errors.Errorf("cannot revoke for type %s, not enabled yet", typ)
	}
305 306
	var parent EventRecord
	if err = rs.db.Last(typ, &parent); err != nil {
307 308
		return err
	}
309 310

	update, err := cur.Remove(sk, e, parent.Event)
311 312 313
	if err != nil {
		return err
	}
314
	if err = rs.addUpdate(tx, typ, update, false); err != nil {
315 316 317 318 319
		return err
	}
	return nil
}

320
// Accumulator methods
321

322 323 324 325 326
func (rs *RevocationStorage) currentAccumulator(tx revStorage, typ CredentialTypeIdentifier) (
	*revocation.SignedAccumulator, *revocation.Accumulator, error,
) {
	record := &AccumulatorRecord{}
	var err error
327
	if rs.sqlMode {
328
		if err = tx.Last(typ, record); err != nil {
329
			if gorm.IsRecordNotFoundError(err) {
330
				return nil, nil, nil
331
			}
332
		}
333
	} else {
334 335 336
		u := rs.memdb.Latest(typ, 0)
		if u == nil {
			return nil, nil, nil
337
		}
338
		record.SignedAccumulator = u.SignedAccumulator
339 340
	}

341
	pk, err := rs.Keys.PublicKey(typ.IssuerIdentifier(), record.PKIndex)
342
	if err != nil {
343
		return nil, nil, err
344
	}
345 346 347
	acc, err := record.UnmarshalVerify(pk)
	if err != nil {
		return nil, nil, err
348
	}
349
	return record.SignedAccumulator, acc, nil
350 351
}

352 353 354
// Methods to update from remote revocation server

func (rs *RevocationStorage) UpdateDB(typ CredentialTypeIdentifier) error {
355
	update, err := rs.client.FetchUpdateLatest(typ, revocationUpdateCount)
356
	if err != nil {
357
		return err
358
	}
359

360
	if err = rs.AddUpdate(typ, update); err != nil {
361 362 363 364 365 366
		return err
	}

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

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

380 381
// 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.
382 383 384 385 386 387 388 389 390
func (rs *RevocationStorage) SaveIssuanceRecord(typ CredentialTypeIdentifier, rec *IssuanceRecord, sk *gabi.PrivateKey) error {
	credtype := rs.conf.CredentialTypes[typ]
	if credtype == nil {
		return errors.New("unknown credential type")
	}
	if !credtype.SupportsRevocation() {
		return errors.New("cannot save issuance record: credential type does not support revocation")
	}

391
	// Just store it if we are the revocation server for this credential type
392 393
	settings := rs.getSettings(typ)
	if settings.Mode == RevocationModeServer {
394
		return rs.AddIssuanceRecord(rec)
395 396
	}

397
	// We have to send it, sign it first
398 399 400
	if settings.ServerURL == "" {
		return errors.New("cannot send issuance record: no server_url configured")
	}
401
	rsk, err := sk.RevocationKey()
402 403 404
	if err != nil {
		return err
	}
405
	return rs.client.PostIssuanceRecord(typ, rsk, rec, settings.ServerURL)
406 407
}

408 409 410
// Misscelaneous methods

func (rs *RevocationStorage) Load(debug bool, connstr string, settings map[CredentialTypeIdentifier]*RevocationSetting) error {
411
	var t *CredentialTypeIdentifier
412

413 414
	for typ, s := range settings {
		switch s.Mode {
415 416 417 418
		case RevocationModeServer:
			if s.ServerURL != "" {
				return errors.New("server_url cannot be combined with server mode")
			}
419
			t = &typ
420 421 422
		case RevocationModeProxy:
			t = &typ
		case RevocationModeRequestor: // noop
423
		default:
424 425
			return errors.Errorf(`invalid revocation mode "%s" for %s (supported: "%s", "%s", "%s")`,
				s.Mode, typ, RevocationModeRequestor, RevocationModeServer, RevocationModeProxy)
426
		}
427
	}
428 429 430
	if t != nil && connstr == "" {
		return errors.Errorf("revocation mode for %s requires SQL database but no connection string given", *t)
	}
431 432 433 434 435 436 437 438

	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)
439
		if err != nil {
440
			return err
441
		}
442 443
		rs.db = db
		rs.sqlMode = true
444
	}
445 446 447 448 449
	if settings != nil {
		rs.settings = settings
	} else {
		rs.settings = map[CredentialTypeIdentifier]*RevocationSetting{}
	}
450 451 452 453 454 455
	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)
		}
	}
456 457 458
	rs.client = RevocationClient{Conf: rs.conf}
	rs.Keys = RevocationKeys{Conf: rs.conf}
	return nil
459 460
}

461 462 463
func (rs *RevocationStorage) Close() error {
	if rs.db != nil {
		return rs.db.Close()
464 465 466 467
	}
	return nil
}

468
// SetRevocationUpdates retrieves the latest revocation records from the database, and attaches
469 470
// them to the request, for each credential type for which a nonrevocation proof is requested in
// b.Revocation.
471
func (rs *RevocationStorage) SetRevocationUpdates(b *BaseRequest) error {
472 473
	if len(b.Revocation) == 0 {
		return nil
474
	}
475
	var err error
476
	b.RevocationUpdates = make(map[CredentialTypeIdentifier]*revocation.Update, len(b.Revocation))
477
	for _, credid := range b.Revocation {
478 479 480
		if !rs.conf.CredentialTypes[credid].SupportsRevocation() {
			return errors.Errorf("cannot request nonrevocation proof for %s: revocation not enabled in scheme")
		}
Sietse Ringers's avatar
Sietse Ringers committed
481
		if err = rs.UpdateIfOld(credid); err != nil {
482 483 484 485 486 487 488 489 490 491 492 493
			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
			}
494
		}
495
		b.RevocationUpdates[credid], err = rs.UpdateLatest(credid, revocationUpdateCount)
496 497 498
		if err != nil {
			return err
		}
499
	}
500 501 502 503 504 505
	return nil
}

func (rs *RevocationStorage) getSettings(typ CredentialTypeIdentifier) *RevocationSetting {
	if rs.settings[typ] == nil {
		rs.settings[typ] = &RevocationSetting{}
506
	}
507 508 509 510 511
	s := rs.settings[typ]
	if s.MaxNonrevocationDuration == 0 {
		s.MaxNonrevocationDuration = revocationMaxAccumulatorAge
	}
	return s
512 513
}

514
func (client RevocationClient) PostUpdate(typ CredentialTypeIdentifier, urls []string, update *revocation.Update) {
515
	transport := NewHTTPTransport("")
516
	transport.Binary = true
517
	for _, url := range urls {
518 519
		err := transport.Post(fmt.Sprintf("%s/revocation/update/%s", url, typ.String()), nil, update)
		if err != nil {
520 521
			Logger.Warn("error sending revocation update", err)
		}
522
	}
523 524
}

525 526 527 528 529
func (client RevocationClient) PostIssuanceRecord(typ CredentialTypeIdentifier, sk *revocation.PrivateKey, rec *IssuanceRecord, url string) error {
	message, err := signed.MarshalSign(sk.ECDSA, rec)
	if err != nil {
		return err
	}
530
	return NewHTTPTransport(url).Post(
531
		fmt.Sprintf("revocation/issuancerecord/%s/%d", typ, sk.Counter), nil, []byte(message),
532 533 534 535
	)
}

// FetchRevocationRecords gets revocation update messages from the revocation server, of the specified index and greater.
536 537
func (client RevocationClient) FetchUpdateFrom(typ CredentialTypeIdentifier, index uint64) (*revocation.Update, error) {
	return client.fetchUpdate(typ, "updatefrom", index)
538
}
539

540 541 542 543 544
func (client RevocationClient) FetchUpdateLatest(typ CredentialTypeIdentifier, count uint64) (*revocation.Update, error) {
	return client.fetchUpdate(typ, "updatelatest", count)
}

func (client RevocationClient) fetchUpdate(typ CredentialTypeIdentifier, u string, i uint64) (*revocation.Update, error) {
545 546 547 548 549 550 551
	var (
		err       error
		errs      multierror.Error
		update    = &revocation.Update{}
		transport = NewHTTPTransport("")
	)
	transport.Binary = true
552 553
	for _, url := range client.Conf.CredentialTypes[typ].RevocationServers {
		transport.Server = url
554
		err = transport.Get(fmt.Sprintf("revocation/%s/%s/%d", u, typ, i), &update)
555
		if err == nil {
556
			return update, nil
557 558 559
		} else {
			errs.Errors = append(errs.Errors, err)
		}
560
	}
561
	return nil, errors.WrapPrefix(errs, "failed to download revocation update", 0)
562 563
}

564 565
func (rs RevocationKeys) PrivateKey(issid IssuerIdentifier) (*revocation.PrivateKey, error) {
	sk, err := rs.Conf.PrivateKey(issid)
566
	if err != nil {
567
		return nil, err
568 569
	}
	if sk == nil {
570
		return nil, errors.Errorf("unknown private key: %s", issid)
571
	}
572
	revsk, err := sk.RevocationKey()
573
	if err != nil {
574
		return nil, err
575
	}
576 577
	return revsk, nil
}
578

579 580
func (rs RevocationKeys) PublicKey(issid IssuerIdentifier, counter uint) (*revocation.PublicKey, error) {
	pk, err := rs.Conf.PublicKey(issid, int(counter))
581
	if err != nil {
582
		return nil, err
583
	}
584 585
	if pk == nil {
		return nil, errors.Errorf("unknown public key: %s-%d", issid, counter)
586
	}
587 588 589
	revpk, err := pk.RevocationKey()
	if err != nil {
		return nil, err
590
	}
591
	return revpk, nil
592
}