revocation.go 18.4 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(typ, update); 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 215
func (rs *RevocationStorage) AddUpdate(typ CredentialTypeIdentifier, record *revocation.Update) error {
	return rs.addUpdate(rs.db, typ, record)
216
}
217

218
func (rs *RevocationStorage) addUpdate(tx revStorage, typ CredentialTypeIdentifier, update *revocation.Update) 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
		if err = tx.Upsert(&AccumulatorRecord{SignedAccumulator: update.SignedAccumulator, CredType: typ}); err != nil {
231
			return err
232
		}
233 234 235 236 237
		for _, event := range update.Events {
			if err = tx.Insert(&EventRecord{Event: event, CredType: typ}); err != nil {
				return err
			}
		}
238
	} else {
239
		rs.memdb.Insert(typ, update)
240 241
	}

242
	s := rs.getSettings(typ)
243
	s.updated = time.Now()
244 245
	// POST record to listeners, if any, asynchroniously
	go rs.client.PostUpdate(typ, s.PostURLs, update)
246 247 248

	return nil
}
249

250 251 252 253
// Issuance records

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

256 257
func (rs *RevocationStorage) AddIssuanceRecord(r *IssuanceRecord) error {
	return rs.db.Insert(r)
258 259
}

260 261 262 263 264
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
265
	}
266 267
	return &r, nil
}
268

269 270
// Revocation methods

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

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

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

	update, err := cur.Remove(sk, e, parent.Event)
307 308 309
	if err != nil {
		return err
	}
310
	if err = rs.addUpdate(tx, typ, update); err != nil {
311 312 313 314 315
		return err
	}
	return nil
}

316
// Accumulator methods
317

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

337
	pk, err := rs.Keys.PublicKey(typ.IssuerIdentifier(), record.PKIndex)
338
	if err != nil {
339
		return nil, nil, err
340
	}
341 342 343
	acc, err := record.UnmarshalVerify(pk)
	if err != nil {
		return nil, nil, err
344
	}
345
	return record.SignedAccumulator, acc, nil
346 347
}

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

func (rs *RevocationStorage) UpdateDB(typ CredentialTypeIdentifier) error {
351
	update, err := rs.client.FetchUpdateLatest(typ, revocationUpdateCount)
352
	if err != nil {
353
		return err
354
	}
355

356
	if err = rs.AddUpdate(typ, update); err != nil {
357 358 359 360 361 362
		return err
	}

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

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

376 377
// 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.
378 379 380 381 382 383 384 385 386
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")
	}

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

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

404 405 406
// Misscelaneous methods

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

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

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

457 458 459
func (rs *RevocationStorage) Close() error {
	if rs.db != nil {
		return rs.db.Close()
460 461 462 463
	}
	return nil
}

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

func (rs *RevocationStorage) getSettings(typ CredentialTypeIdentifier) *RevocationSetting {
	if rs.settings[typ] == nil {
		rs.settings[typ] = &RevocationSetting{}
502
	}
503 504 505 506 507
	s := rs.settings[typ]
	if s.MaxNonrevocationDuration == 0 {
		s.MaxNonrevocationDuration = revocationMaxAccumulatorAge
	}
	return s
508 509
}

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

520 521 522 523 524
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
	}
525
	return NewHTTPTransport(url).Post(
526
		fmt.Sprintf("revocation/issuancerecord/%s/%d", typ, sk.Counter), nil, []byte(message),
527 528 529 530
	)
}

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

535 536 537 538 539 540 541
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) {
	records := &revocation.Update{}
	var err error
542 543 544 545
	var errs multierror.Error
	transport := NewHTTPTransport("")
	for _, url := range client.Conf.CredentialTypes[typ].RevocationServers {
		transport.Server = url
546
		err = transport.Get(fmt.Sprintf("revocation/%s/%s/%d", u, typ, i), &records)
547 548 549 550 551
		if err == nil {
			return records, nil
		} else {
			errs.Errors = append(errs.Errors, err)
		}
552
	}
553
	return nil, errors.WrapPrefix(errs, "failed to download revocation update", 0)
554 555
}

556 557
func (rs RevocationKeys) PrivateKey(issid IssuerIdentifier) (*revocation.PrivateKey, error) {
	sk, err := rs.Conf.PrivateKey(issid)
558
	if err != nil {
559
		return nil, err
560 561
	}
	if sk == nil {
562
		return nil, errors.Errorf("unknown private key: %s", issid)
563
	}
564
	revsk, err := sk.RevocationKey()
565
	if err != nil {
566
		return nil, err
567
	}
568 569
	return revsk, nil
}
570

571 572
func (rs RevocationKeys) PublicKey(issid IssuerIdentifier, counter uint) (*revocation.PublicKey, error) {
	pk, err := rs.Conf.PublicKey(issid, int(counter))
573
	if err != nil {
574
		return nil, err
575
	}
576 577
	if pk == nil {
		return nil, errors.Errorf("unknown public key: %s-%d", issid, counter)
578
	}
579 580 581
	revpk, err := pk.RevocationKey()
	if err != nil {
		return nil, err
582
	}
583
	return revpk, nil
584
}