revocation.go 18.7 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/big"
12
	"github.com/privacybydesign/gabi/revocation"
13
	"github.com/privacybydesign/gabi/signed"
14 15
)

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

		Keys   RevocationKeys
		client RevocationClient
29 30
	}

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

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

Sietse Ringers's avatar
Sietse Ringers committed
42
	// RevocationSetting contains revocation settings for a given credential type.
43
	RevocationSetting struct {
44 45 46
		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
47
		ServerURL                string         `json:"server_url" mapstructure:"server_url"`
48 49 50 51 52

		// 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
53 54
	}

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

Sietse Ringers's avatar
Sietse Ringers committed
59 60 61
	// 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.
62 63
	RevocationRecord struct {
		revocation.Record `gorm:"embedded"`
64
		PublicKeyIndex    uint
65
		CredType          CredentialTypeIdentifier `gorm:"primary_key"`
66 67 68 69 70 71 72 73 74
	}

	TimeRecord struct {
		Index      uint64
		Start, End int64
	}

	// 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
const (
Sietse Ringers's avatar
Sietse Ringers committed
85 86
	// RevocationModeRequestor is the default revocation mode in which only RevocationRecord instances
	// are consumed for issuance or verification. Uses an in-memory store.
87
	RevocationModeRequestor RevocationMode = ""
Sietse Ringers's avatar
Sietse Ringers committed
88 89 90 91 92 93 94 95

	// 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"

96
	// RevocationModeServer indicates that this is a revocation server for a credential type.
Sietse Ringers's avatar
Sietse Ringers committed
97 98 99 100
	// 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.
101
	// In addition this mode exposes the same endpoints as RevocationModeProxy.
Sietse Ringers's avatar
Sietse Ringers committed
102 103 104 105 106
	RevocationModeServer RevocationMode = "server"

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

108 109 110
	// 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
111
	// against a 'younger' accumulator.
112
	revocationMaxAccumulatorAge uint = 5 * 60
113 114
)

115
// Revocation record methods
116

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

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

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

Sietse Ringers's avatar
Sietse Ringers committed
149 150 151 152 153 154 155 156 157 158 159
// 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
160 161
// at the specified index, that is, all records whose end index is greater than or equal to
// the specified index.
162 163 164
func (rs *RevocationStorage) RevocationRecords(typ CredentialTypeIdentifier, index uint64) ([]*RevocationRecord, error) {
	var records []*RevocationRecord
	return records, rs.db.From(typ, "end_index", index, &records)
165 166
}

167 168 169 170 171 172 173 174
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)
175
	}
176 177
	if len(records) == 0 {
		return nil, gorm.ErrRecordNotFound
178
	}
179
	return records, nil
180 181
}

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

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

195 196 197
	return nil
}

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

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

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

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

	return nil
}
231

232 233 234 235
// Issuance records

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

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

242 243 244 245 246
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
247
	}
248 249
	return &r, nil
}
250

251 252
// Revocation methods

Sietse Ringers's avatar
Sietse Ringers committed
253 254
// 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,
255
// and updating the revocation database on disk.
256
func (rs *RevocationStorage) Revoke(typ CredentialTypeIdentifier, key string, sk *revocation.PrivateKey) error {
Sietse Ringers's avatar
Sietse Ringers committed
257 258
	if rs.getSettings(typ).Mode != RevocationModeServer {
		return errors.Errorf("cannot revoke %s", typ)
259
	}
260

261 262 263 264 265 266 267 268 269 270
	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
		}
271
		return rs.revokeAttr(tx, typ, sk, cr.Attr)
272 273 274
	})
}

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

313
// Accumulator methods
314

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

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

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

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

349 350 351 352
// Methods to update from remote revocation server

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

	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
364 365
}

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

377 378 379 380
// 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 {
	// Just store it if we are the revocation server for this credential type
381 382
	settings := rs.getSettings(typ)
	if settings.Mode == RevocationModeServer {
383
		return rs.AddIssuanceRecord(rec)
384 385
	}

386
	// We have to send it, sign it first
387 388 389
	if settings.ServerURL == "" {
		return errors.New("cannot send issuance record: no server_url configured")
	}
390 391 392 393
	credtype := rs.conf.CredentialTypes[typ]
	if credtype == nil {
		return errors.New("unknown credential type")
	}
394 395
	if !credtype.SupportsRevocation() {
		return errors.New("cannot send issuance record: credential type does not support revocation")
396 397
	}
	sk, err := rs.Keys.PrivateKey(typ.IssuerIdentifier())
398 399 400
	if err != nil {
		return err
	}
401
	message, err := signed.MarshalSign(sk.ECDSA, rec)
402 403 404
	if err != nil {
		return err
	}
405

406
	return rs.client.PostIssuanceRecord(typ, sk.Counter, message, settings.ServerURL)
407 408
}

409 410 411
// Misscelaneous methods

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

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

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

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

469 470 471 472 473 474
// 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
475
	}
476 477 478
	var err error
	b.RevocationUpdates = make(map[CredentialTypeIdentifier][]*RevocationRecord, len(b.Revocation))
	for _, credid := range b.Revocation {
479 480 481
		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
482
		if err = rs.UpdateIfOld(credid); err != nil {
483 484 485 486 487 488 489 490 491 492 493 494
			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
			}
495 496 497 498 499
		}
		b.RevocationUpdates[credid], err = rs.LatestRevocationRecords(credid, revocationUpdateCount)
		if err != nil {
			return err
		}
500
	}
501 502 503 504 505 506
	return nil
}

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

515
func (RevocationClient) PostRevocationRecords(urls []string, records []*RevocationRecord) {
516
	transport := NewHTTPTransport("")
517
	for _, url := range urls {
518
		if err := transport.Post(url+"/revocation/records", nil, &records); err != nil {
519 520
			Logger.Warn("error sending revocation update", err)
		}
521
	}
522 523
}

524 525
func (client RevocationClient) PostIssuanceRecord(typ CredentialTypeIdentifier, counter uint, message signed.Message, url string) error {
	return NewHTTPTransport(url).Post(
526
		fmt.Sprintf("revocation/issuancerecord/%s/%d", typ, counter), nil, []byte(message),
527 528 529 530 531 532
	)
}

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

548 549
func (client RevocationClient) FetchLatestRevocationRecords(typ CredentialTypeIdentifier, count uint64) ([]*RevocationRecord, error) {
	var records []*RevocationRecord
550 551 552 553
	var errs multierror.Error
	transport := NewHTTPTransport("")
	for _, url := range client.Conf.CredentialTypes[typ].RevocationServers {
		transport.Server = url
554
		err := transport.Get(fmt.Sprintf("revocation/latestrecords/%s/%d", typ, count), &records)
555 556 557 558 559
		if err == nil {
			return records, nil
		} else {
			errs.Errors = append(errs.Errors, err)
		}
560
	}
561
	return nil, errors.WrapPrefix(errs, "failed to download latest revocation records", 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
}