client.go 25.9 KB
Newer Older
1
package irmaclient
2
3

import (
4
	"crypto/rand"
Sietse Ringers's avatar
Sietse Ringers committed
5
	"math/big"
Sietse Ringers's avatar
Sietse Ringers committed
6
	"sort"
7
	"time"
Sietse Ringers's avatar
Sietse Ringers committed
8

9
	"github.com/credentials/go-go-gadget-paillier"
10
	raven "github.com/getsentry/raven-go"
Sietse Ringers's avatar
Sietse Ringers committed
11
	"github.com/go-errors/errors"
12
	"github.com/mhe/gabi"
13
14
	"github.com/privacybydesign/irmago"
	"github.com/privacybydesign/irmago/internal/fs"
15
16
)

17
// This file contains most methods of the Client (c.f. session.go
Sietse Ringers's avatar
Sietse Ringers committed
18
19
// and updates.go).
//
Sietse Ringers's avatar
Sietse Ringers committed
20
21
22
23
24
25
26
27
// Clients are the main entry point into this package for the user of this package.
// The Client struct:
// - (De)serializes credentials and keyshare server information
// from storage, as well as logs of earlier IRMA sessions
// - it provides access to the attributes and all related information of its credentials,
// - it is the starting point for new IRMA sessions;
// - and it computes some of the messages in the client side of the IRMA protocol.
//
Sietse Ringers's avatar
Sietse Ringers committed
28
29
30
31
32
33
34
// The storage of credentials is split up in several parts:
//
// - The CL-signature of each credential is stored separately, so that we can
// load it on demand (i.e., during an IRMA session), instead of immediately
// at initialization.
//
// - The attributes of all credentials are stored together, as they all
35
// immediately need to be available anyway.
Sietse Ringers's avatar
Sietse Ringers committed
36
37
38
39
40
//
// - The secret key (the zeroth attribute of every credential), being the same
// across all credentials, is stored only once in a separate file (storing this
// in multiple places would be bad).

41
type Client struct {
Sietse Ringers's avatar
Sietse Ringers committed
42
	// Stuff we manage on disk
43
	secretkey        *secretKey
44
45
46
	attributes       map[irma.CredentialTypeIdentifier][]*irma.AttributeList
	credentials      map[irma.CredentialTypeIdentifier]map[int]*credential
	keyshareServers  map[irma.SchemeManagerIdentifier]*keyshareServer
47
	paillierKeyCache *paillierPrivateKey
Sietse Ringers's avatar
Sietse Ringers committed
48
	logs             []*LogEntry
Sietse Ringers's avatar
Sietse Ringers committed
49
	updates          []update
50

Sietse Ringers's avatar
Sietse Ringers committed
51
52
53
54
	// Where we store/load it to/from
	storage storage

	// Other state
55
	Preferences              Preferences
56
	Configuration            *irma.Configuration
57
58
59
	irmaConfigurationPath    string
	androidStoragePath       string
	handler                  ClientHandler
60
	state                    *issuanceState
61
62
}

63
64
65
66
// SentryDSN should be set in the init() function
// Setting it to an empty string means no crash reports
var SentryDSN = ""

67
68
type Preferences struct {
	EnableCrashReporting bool
69
70
}

71
var defaultPreferences = Preferences{
72
	EnableCrashReporting: true,
73
74
}

75
// KeyshareHandler is used for asking the user for his email address and PIN,
76
// for enrolling at a keyshare server.
77
type KeyshareHandler interface {
Tomas's avatar
Tomas committed
78
	EnrollmentFailure(manager irma.SchemeManagerIdentifier, err error)
79
	EnrollmentSuccess(manager irma.SchemeManagerIdentifier)
80
81
}

82
83
84
85
type ChangePinHandler interface {
	ChangePinFailure(manager irma.SchemeManagerIdentifier, err error)
	ChangePinSuccess(manager irma.SchemeManagerIdentifier)
	ChangePinIncorrect(manager irma.SchemeManagerIdentifier)
86
87
}

Sietse Ringers's avatar
Sietse Ringers committed
88
89
// ClientHandler informs the user that the configuration or the list of attributes
// that this client uses has been updated.
90
91
type ClientHandler interface {
	KeyshareHandler
92
	ChangePinHandler
93

94
	UpdateConfiguration(new *irma.IrmaIdentifierSet)
95
	UpdateAttributes()
Sietse Ringers's avatar
Sietse Ringers committed
96
97
}

98
99
100
101
type secretKey struct {
	Key *big.Int
}

102
// New creates a new Client that uses the directory
103
104
105
106
// specified by storagePath for (de)serializing itself. irmaConfigurationPath
// is the path to a (possibly readonly) folder containing irma_configuration;
// androidStoragePath is an optional path to the files of the old android app
// (specify "" if you do not want to parse the old android app files),
107
// and handler is used for informing the user of new stuff, and when a
108
// enrollment to a keyshare server needs to happen.
109
// The client returned by this function has been fully deserialized
110
111
// and is ready for use.
//
Sietse Ringers's avatar
Sietse Ringers committed
112
113
// NOTE: It is the responsibility of the caller that there exists a (properly
// protected) directory at storagePath!
114
func New(
115
116
117
	storagePath string,
	irmaConfigurationPath string,
	androidStoragePath string,
118
	handler ClientHandler,
119
) (*Client, error) {
120
	var err error
121
	if err = fs.AssertPathExists(storagePath); err != nil {
122
123
		return nil, err
	}
124
	if err = fs.AssertPathExists(irmaConfigurationPath); err != nil {
125
126
127
		return nil, err
	}

128
	cm := &Client{
129
130
131
		credentials:           make(map[irma.CredentialTypeIdentifier]map[int]*credential),
		keyshareServers:       make(map[irma.SchemeManagerIdentifier]*keyshareServer),
		attributes:            make(map[irma.CredentialTypeIdentifier][]*irma.AttributeList),
132
133
		irmaConfigurationPath: irmaConfigurationPath,
		androidStoragePath:    androidStoragePath,
134
		handler:               handler,
135
136
	}

137
	cm.Configuration, err = irma.NewConfiguration(storagePath+"/irma_configuration", irmaConfigurationPath)
138
139
140
	if err != nil {
		return nil, err
	}
141

142
	schemeMgrErr := cm.Configuration.ParseOrRestoreFolder()
143
144
145
146
147
	// If schemMgrErr is of type SchemeManagerError, we continue and
	// return it at the end; otherwise bail out now
	_, isSchemeMgrErr := schemeMgrErr.(*irma.SchemeManagerError)
	if schemeMgrErr != nil && !isSchemeMgrErr {
		return nil, schemeMgrErr
148
	}
149
150

	// Ensure storage path exists, and populate it with necessary files
151
	cm.storage = storage{storagePath: storagePath, Configuration: cm.Configuration}
Sietse Ringers's avatar
Sietse Ringers committed
152
	if err = cm.storage.EnsureStorageExists(); err != nil {
153
154
155
		return nil, err
	}

156
	if cm.Preferences, err = cm.storage.LoadPreferences(); err != nil {
157
158
		return nil, err
	}
159
	cm.applyPreferences()
160

161
	// Perform new update functions from clientUpdates, if any
162
163
164
165
166
	if err = cm.update(); err != nil {
		return nil, err
	}

	// Load our stuff
Sietse Ringers's avatar
Sietse Ringers committed
167
	if cm.secretkey, err = cm.storage.LoadSecretKey(); err != nil {
168
169
		return nil, err
	}
Sietse Ringers's avatar
Sietse Ringers committed
170
	if cm.attributes, err = cm.storage.LoadAttributes(); err != nil {
171
172
		return nil, err
	}
173
	if cm.keyshareServers, err = cm.storage.LoadKeyshareServers(); err != nil {
174
175
		return nil, err
	}
176
	if cm.paillierKeyCache, err = cm.storage.LoadPaillierKeys(); err != nil {
177
178
		return nil, err
	}
179
180
181
	if cm.paillierKeyCache == nil {
		cm.paillierKey(false)
	}
182

183
	if len(cm.UnenrolledSchemeManagers()) > 1 {
184
185
186
		return nil, errors.New("Too many keyshare servers")
	}

187
	return cm, schemeMgrErr
188
189
}

190
// CredentialInfoList returns a list of information of all contained credentials.
191
192
func (client *Client) CredentialInfoList() irma.CredentialInfoList {
	list := irma.CredentialInfoList([]*irma.CredentialInfo{})
193

194
	for _, attrlistlist := range client.attributes {
195
196
		for index, attrlist := range attrlistlist {
			info := attrlist.Info()
197
198
199
			if info == nil {
				continue
			}
200
			info.Index = index
201
			list = append(list, info)
Sietse Ringers's avatar
Sietse Ringers committed
202
203
		}
	}
204

Sietse Ringers's avatar
Sietse Ringers committed
205
206
207
208
	sort.Sort(list)
	return list
}

209
// addCredential adds the specified credential to the Client, saving its signature
Sietse Ringers's avatar
Sietse Ringers committed
210
// imediately, and optionally cm.attributes as well.
211
func (client *Client) addCredential(cred *credential, storeAttributes bool) (err error) {
212
213
214
215
	id := irma.NewCredentialTypeIdentifier("")
	if cred.CredentialType() != nil {
		id = cred.CredentialType().Identifier()
	}
Sietse Ringers's avatar
Sietse Ringers committed
216

217
	// Don't add duplicate creds
218
	for _, attrlistlist := range client.attributes {
219
		for _, attrs := range attrlistlist {
220
			if attrs.Hash() == cred.AttributeList().Hash() {
221
222
223
224
225
226
				return nil
			}
		}
	}

	// If this is a singleton credential type, ensure we have at most one by removing any previous instance
227
	if !id.Empty() && cred.CredentialType().IsSingleton && len(client.attrs(id)) > 0 {
228
		client.remove(id, 0, false) // Index is 0, because if we're here we have exactly one
229
230
231
	}

	// Append the new cred to our attributes and credentials
232
	client.attributes[id] = append(client.attrs(id), cred.AttributeList())
233
234
235
236
237
238
	if !id.Empty() {
		if _, exists := client.credentials[id]; !exists {
			client.credentials[id] = make(map[int]*credential)
		}
		counter := len(client.attributes[id]) - 1
		client.credentials[id][counter] = cred
Sietse Ringers's avatar
Sietse Ringers committed
239
240
	}

241
	if err = client.storage.StoreSignature(cred); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
242
243
244
		return
	}
	if storeAttributes {
245
		err = client.storage.StoreAttributes(client.attributes)
Sietse Ringers's avatar
Sietse Ringers committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
	}
	return
}

func generateSecretKey() (*secretKey, error) {
	key, err := gabi.RandomBigInt(gabi.DefaultSystemParameters[1024].Lm)
	if err != nil {
		return nil, err
	}
	return &secretKey{Key: key}, nil
}

// Removal methods

260
func (client *Client) remove(id irma.CredentialTypeIdentifier, index int, storenow bool) error {
261
	// Remove attributes
262
	list, exists := client.attributes[id]
263
264
265
266
	if !exists || index >= len(list) {
		return errors.Errorf("Can't remove credential %s-%d: no such credential", id.String(), index)
	}
	attrs := list[index]
267
	client.attributes[id] = append(list[:index], list[index+1:]...)
268
	if storenow {
269
		if err := client.storage.StoreAttributes(client.attributes); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
270
271
			return err
		}
272
273
274
	}

	// Remove credential
275
	if creds, exists := client.credentials[id]; exists {
276
		if _, exists := creds[index]; exists {
Sietse Ringers's avatar
Sietse Ringers committed
277
			delete(creds, index)
278
			client.credentials[id] = creds
279
280
281
282
		}
	}

	// Remove signature from storage
283
	if err := client.storage.DeleteSignature(attrs); err != nil {
284
285
286
		return err
	}

287
	removed := map[irma.CredentialTypeIdentifier][]irma.TranslatedString{}
288
289
290
	removed[id] = attrs.Strings()

	if storenow {
291
		return client.addLogEntry(&LogEntry{
292
			Type:    actionRemoval,
293
			Time:    irma.Timestamp(time.Now()),
294
295
296
297
			Removed: removed,
		})
	}
	return nil
298
299
}

Sietse Ringers's avatar
Sietse Ringers committed
300
// RemoveCredential removes the specified credential.
301
func (client *Client) RemoveCredential(id irma.CredentialTypeIdentifier, index int) error {
302
	return client.remove(id, index, true)
303
304
}

Sietse Ringers's avatar
Sietse Ringers committed
305
// RemoveCredentialByHash removes the specified credential.
306
307
func (client *Client) RemoveCredentialByHash(hash string) error {
	cred, index, err := client.credentialByHash(hash)
308
309
310
	if err != nil {
		return err
	}
311
	return client.RemoveCredential(cred.CredentialType().Identifier(), index)
312
313
}

Sietse Ringers's avatar
Sietse Ringers committed
314
// RemoveAllCredentials removes all credentials.
315
func (client *Client) RemoveAllCredentials() error {
316
	removed := map[irma.CredentialTypeIdentifier][]irma.TranslatedString{}
317
	for _, attrlistlist := range client.attributes {
Sietse Ringers's avatar
Sietse Ringers committed
318
319
320
321
		for _, attrs := range attrlistlist {
			if attrs.CredentialType() != nil {
				removed[attrs.CredentialType().Identifier()] = attrs.Strings()
			}
322
			client.storage.DeleteSignature(attrs)
323
324
		}
	}
325
	client.attributes = map[irma.CredentialTypeIdentifier][]*irma.AttributeList{}
326
	if err := client.storage.StoreAttributes(client.attributes); err != nil {
327
328
		return err
	}
329
330
331

	logentry := &LogEntry{
		Type:    actionRemoval,
332
		Time:    irma.Timestamp(time.Now()),
333
334
		Removed: removed,
	}
335
	if err := client.addLogEntry(logentry); err != nil {
336
337
		return err
	}
338
	return client.storage.StoreLogs(client.logs)
339
340
}

341
// Attribute and credential getter methods
Sietse Ringers's avatar
Sietse Ringers committed
342

Sietse Ringers's avatar
Sietse Ringers committed
343
// attrs returns cm.attributes[id], initializing it to an empty slice if neccesary
344
func (client *Client) attrs(id irma.CredentialTypeIdentifier) []*irma.AttributeList {
345
	list, exists := client.attributes[id]
Sietse Ringers's avatar
Sietse Ringers committed
346
	if !exists {
347
		list = make([]*irma.AttributeList, 0, 1)
348
		client.attributes[id] = list
Sietse Ringers's avatar
Sietse Ringers committed
349
350
351
352
353
	}
	return list
}

// creds returns cm.credentials[id], initializing it to an empty map if neccesary
354
func (client *Client) creds(id irma.CredentialTypeIdentifier) map[int]*credential {
355
	list, exists := client.credentials[id]
Sietse Ringers's avatar
Sietse Ringers committed
356
	if !exists {
Sietse Ringers's avatar
Sietse Ringers committed
357
		list = make(map[int]*credential)
358
		client.credentials[id] = list
Sietse Ringers's avatar
Sietse Ringers committed
359
360
361
362
	}
	return list
}

Sietse Ringers's avatar
Sietse Ringers committed
363
// Attributes returns the attribute list of the requested credential, or nil if we do not have it.
364
func (client *Client) Attributes(id irma.CredentialTypeIdentifier, counter int) (attributes *irma.AttributeList) {
365
	list := client.attrs(id)
Sietse Ringers's avatar
Sietse Ringers committed
366
	if len(list) <= counter {
Sietse Ringers's avatar
Sietse Ringers committed
367
368
369
370
371
		return
	}
	return list[counter]
}

372
373
func (client *Client) credentialByHash(hash string) (*credential, int, error) {
	for _, attrlistlist := range client.attributes {
374
		for index, attrs := range attrlistlist {
375
			if attrs.Hash() == hash {
376
				cred, err := client.credential(attrs.CredentialType().Identifier(), index)
377
378
379
380
381
382
383
				return cred, index, err
			}
		}
	}
	return nil, 0, nil
}

384
func (client *Client) credentialByID(id irma.CredentialIdentifier) (*credential, error) {
385
	if _, exists := client.attributes[id.Type]; !exists {
Sietse Ringers's avatar
Sietse Ringers committed
386
387
		return nil, nil
	}
388
	for index, attrs := range client.attributes[id.Type] {
389
		if attrs.Hash() == id.Hash {
390
			return client.credential(attrs.CredentialType().Identifier(), index)
Sietse Ringers's avatar
Sietse Ringers committed
391
392
393
		}
	}
	return nil, nil
394
395
}

Sietse Ringers's avatar
Sietse Ringers committed
396
// credential returns the requested credential, or nil if we do not have it.
397
func (client *Client) credential(id irma.CredentialTypeIdentifier, counter int) (cred *credential, err error) {
Sietse Ringers's avatar
Sietse Ringers committed
398
	// If the requested credential is not in credential map, we check if its attributes were
399
	// deserialized during New(). If so, there should be a corresponding signature file,
Sietse Ringers's avatar
Sietse Ringers committed
400
	// so we read that, construct the credential, and add it to the credential map
401
402
	if _, exists := client.creds(id)[counter]; !exists {
		attrs := client.Attributes(id, counter)
Sietse Ringers's avatar
Sietse Ringers committed
403
404
405
		if attrs == nil { // We do not have the requested cred
			return
		}
406
		sig, err := client.storage.LoadSignature(attrs)
Sietse Ringers's avatar
Sietse Ringers committed
407
408
409
410
411
412
413
		if err != nil {
			return nil, err
		}
		if sig == nil {
			err = errors.New("signature file not found")
			return nil, err
		}
414
		pk, err := attrs.PublicKey()
415
416
417
		if err != nil {
			return nil, err
		}
418
419
420
		if pk == nil {
			return nil, errors.New("unknown public key")
		}
421
		cred, err := newCredential(&gabi.Credential{
422
			Attributes: append([]*big.Int{client.secretkey.Key}, attrs.Ints...),
423
			Signature:  sig,
424
			Pk:         pk,
425
		}, client.Configuration)
426
427
428
		if err != nil {
			return nil, err
		}
429
		client.credentials[id][counter] = cred
Sietse Ringers's avatar
Sietse Ringers committed
430
431
	}

432
	return client.credentials[id][counter], nil
433
434
}

Sietse Ringers's avatar
Sietse Ringers committed
435
// Methods used in the IRMA protocol
436

437
// Candidates returns a list of attributes present in this client
Sietse Ringers's avatar
Sietse Ringers committed
438
// that satisfy the specified attribute disjunction.
439
440
func (client *Client) Candidates(disjunction *irma.AttributeDisjunction) []*irma.AttributeIdentifier {
	candidates := make([]*irma.AttributeIdentifier, 0, 10)
441
442

	for _, attribute := range disjunction.Attributes {
Sietse Ringers's avatar
Sietse Ringers committed
443
		credID := attribute.CredentialTypeIdentifier()
444
		if !client.Configuration.Contains(credID) {
445
446
			continue
		}
447
		creds := client.attributes[credID]
448
449
450
451
		count := len(creds)
		if count == 0 {
			continue
		}
452
		for _, attrs := range creds {
453
454
455
			if !attrs.IsValid() {
				continue
			}
456
			id := &irma.AttributeIdentifier{Type: attribute, CredentialHash: attrs.Hash()}
457
458
459
			if attribute.IsCredential() {
				candidates = append(candidates, id)
			} else {
460
				val := attrs.UntranslatedAttribute(attribute)
461
				if val == nil {
462
463
					continue
				}
464
				if !disjunction.HasValues() {
465
					candidates = append(candidates, id)
466
467
468
469
470
				} else {
					requiredValue, present := disjunction.Values[attribute]
					if !present || requiredValue == nil || *val == *requiredValue {
						candidates = append(candidates, id)
					}
471
472
473
474
475
476
477
478
				}
			}
		}
	}

	return candidates
}

479
// CheckSatisfiability checks if this client has the required attributes
Sietse Ringers's avatar
Sietse Ringers committed
480
481
// to satisfy the specifed disjunction list. If not, the unsatisfiable disjunctions
// are returned.
482
func (client *Client) CheckSatisfiability(
483
484
485
486
	disjunctions irma.AttributeDisjunctionList,
) ([][]*irma.AttributeIdentifier, irma.AttributeDisjunctionList) {
	candidates := [][]*irma.AttributeIdentifier{}
	missing := irma.AttributeDisjunctionList{}
487
	for i, disjunction := range disjunctions {
488
		candidates = append(candidates, []*irma.AttributeIdentifier{})
489
		candidates[i] = client.Candidates(disjunction)
490
		if len(candidates[i]) == 0 {
491
492
493
			missing = append(missing, disjunction)
		}
	}
494
	return candidates, missing
495
}
496

497
498
func (client *Client) groupCredentials(choice *irma.DisclosureChoice) (map[irma.CredentialIdentifier][]int, error) {
	grouped := make(map[irma.CredentialIdentifier][]int)
499
500
501
	if choice == nil || choice.Attributes == nil {
		return grouped, nil
	}
502
503
504
505
506
507
508
509

	for _, attribute := range choice.Attributes {
		identifier := attribute.Type
		ici := attribute.CredentialIdentifier()

		// If this is the first attribute of its credential type that we encounter
		// in the disclosure choice, then there is no slice yet at grouped[ici]
		if _, present := grouped[ici]; !present {
510
511
			indices := make([]int, 1, 1)
			indices[0] = 1 // Always include metadata
512
513
514
515
516
517
			grouped[ici] = indices
		}

		if identifier.IsCredential() {
			continue // In this case we only disclose the metadata attribute, which is already handled
		}
518
		index, err := client.Configuration.CredentialTypes[identifier.CredentialTypeIdentifier()].IndexOf(identifier)
519
520
521
522
		if err != nil {
			return nil, err
		}

Sietse Ringers's avatar
Sietse Ringers committed
523
		// These indices will be used in the []*big.Int at gabi.credential.Attributes,
524
		// which doesn't know about the secret key and metadata attribute, so +2
525
		grouped[ici] = append(grouped[ici], index+2)
526
527
528
529
530
	}

	return grouped, nil
}

531
// ProofBuilders constructs a list of proof builders for the specified attribute choice.
532
func (client *Client) ProofBuilders(choice *irma.DisclosureChoice, request irma.IrmaSession, issig bool) (gabi.ProofBuilderList, error) {
533
	todisclose, err := client.groupCredentials(choice)
534
535
536
537
	if err != nil {
		return nil, err
	}

538
	builders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
539
	for id, list := range todisclose {
540
		cred, err := client.credentialByID(id)
541
542
543
544
545
		if err != nil {
			return nil, err
		}
		builders = append(builders, cred.Credential.CreateDisclosureProofBuilder(list))
	}
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563

	if issig {
		var sigs []*big.Int
		var disclosed [][]*big.Int
		var s *big.Int
		var d []*big.Int
		for _, builder := range builders {
			s, d = builder.(*gabi.DisclosureProofBuilder).TimestampRequestContributions()
			sigs = append(sigs, s)
			disclosed = append(disclosed, d)
		}
		r := request.(*irma.SignatureRequest)
		r.Timestamp, err = irma.GetTimestamp(r.Message, sigs, disclosed)
		if err != nil {
			return nil, err
		}
	}

564
565
566
567
568
569
570
571
572
573
	return builders, nil
}

// Proofs computes disclosure proofs containing the attributes specified by choice.
func (client *Client) Proofs(choice *irma.DisclosureChoice, request irma.IrmaSession, issig bool) (gabi.ProofList, error) {
	builders, err := client.ProofBuilders(choice, request, issig)
	if err != nil {
		return nil, err
	}

574
	return builders.BuildProofList(request.GetContext(), request.GetNonce(), issig), nil
Sietse Ringers's avatar
Sietse Ringers committed
575
576
}

577
578
// IssuanceProofBuilders constructs a list of proof builders in the issuance protocol
// for the future credentials as well as possibly any disclosed attributes.
579
func (client *Client) IssuanceProofBuilders(request *irma.IssuanceRequest) (gabi.ProofBuilderList, error) {
Sietse Ringers's avatar
Cleanup    
Sietse Ringers committed
580
	state, err := newIssuanceState()
Sietse Ringers's avatar
Sietse Ringers committed
581
582
583
	if err != nil {
		return nil, err
	}
584
	client.state = state
Sietse Ringers's avatar
Sietse Ringers committed
585

586
	proofBuilders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
Sietse Ringers's avatar
Sietse Ringers committed
587
	for _, futurecred := range request.Credentials {
Sietse Ringers's avatar
Sietse Ringers committed
588
		var pk *gabi.PublicKey
589
		pk, err = client.Configuration.PublicKey(futurecred.CredentialTypeID.IssuerIdentifier(), futurecred.KeyCounter)
590
591
592
		if err != nil {
			return nil, err
		}
593
		credBuilder := gabi.NewCredentialBuilder(
594
			pk, request.GetContext(), client.secretkey.Key, state.nonce2)
595
		state.builders = append(state.builders, credBuilder)
Sietse Ringers's avatar
Sietse Ringers committed
596
597
		proofBuilders = append(proofBuilders, credBuilder)
	}
Sietse Ringers's avatar
Sietse Ringers committed
598

599
	disclosures, err := client.ProofBuilders(request.Choice, request, false)
Sietse Ringers's avatar
Sietse Ringers committed
600
601
602
	if err != nil {
		return nil, err
	}
Sietse Ringers's avatar
Sietse Ringers committed
603
	proofBuilders = append(disclosures, proofBuilders...)
Sietse Ringers's avatar
Sietse Ringers committed
604
605
	return proofBuilders, nil
}
Sietse Ringers's avatar
Sietse Ringers committed
606

Sietse Ringers's avatar
Sietse Ringers committed
607
608
// IssueCommitments computes issuance commitments, along with disclosure proofs
// specified by choice.
609
func (client *Client) IssueCommitments(request *irma.IssuanceRequest) (*gabi.IssueCommitmentMessage, error) {
610
	proofBuilders, err := client.IssuanceProofBuilders(request)
Sietse Ringers's avatar
Sietse Ringers committed
611
612
613
	if err != nil {
		return nil, err
	}
614
	list := proofBuilders.BuildProofList(request.GetContext(), request.GetNonce(), false)
615
	return &gabi.IssueCommitmentMessage{Proofs: list, Nonce2: client.state.nonce2}, nil
Sietse Ringers's avatar
Sietse Ringers committed
616
617
}

Sietse Ringers's avatar
Sietse Ringers committed
618
619
// ConstructCredentials constructs and saves new credentials
// using the specified issuance signature messages.
620
func (client *Client) ConstructCredentials(msg []*gabi.IssueSignatureMessage, request *irma.IssuanceRequest) error {
621
	if len(msg) != len(client.state.builders) {
Sietse Ringers's avatar
Sietse Ringers committed
622
623
624
		return errors.New("Received unexpected amount of signatures")
	}

625
626
	// First collect all credentials in a slice, so that if one of them induces an error,
	// we save none of them to fail the session cleanly
627
	gabicreds := []*gabi.Credential{}
Sietse Ringers's avatar
Sietse Ringers committed
628
	for i, sig := range msg {
629
		attrs, err := request.Credentials[i].AttributeList(client.Configuration, getMetadataVersion(request.GetVersion()))
Sietse Ringers's avatar
Sietse Ringers committed
630
631
632
		if err != nil {
			return err
		}
633
		cred, err := client.state.builders[i].ConstructCredential(sig, attrs.Ints)
Sietse Ringers's avatar
Sietse Ringers committed
634
635
636
		if err != nil {
			return err
		}
637
		gabicreds = append(gabicreds, cred)
Sietse Ringers's avatar
Sietse Ringers committed
638
639
	}

640
	for _, gabicred := range gabicreds {
641
		newcred, err := newCredential(gabicred, client.Configuration)
642
643
644
		if err != nil {
			return err
		}
645
		if err = client.addCredential(newcred, true); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
646
647
			return err
		}
Sietse Ringers's avatar
Sietse Ringers committed
648
	}
649

Sietse Ringers's avatar
Sietse Ringers committed
650
	return nil
Sietse Ringers's avatar
Sietse Ringers committed
651
}
652

Sietse Ringers's avatar
Sietse Ringers committed
653
654
// Keyshare server handling

655
// PaillierKey returns a new Paillier key (and generates a new one in a goroutine).
656
657
func (client *Client) paillierKey(wait bool) *paillierPrivateKey {
	cached := client.paillierKeyCache
Sietse Ringers's avatar
Sietse Ringers committed
658
	ch := make(chan bool)
659

660
661
	// Would just write client.paillierKeyCache instead of cached here, but the worker
	// modifies client.paillierKeyCache, and we must be sure that the boolean here and
662
	// the if-clause below match.
663
	go client.paillierKeyWorker(cached == nil && wait, ch)
664
	if cached == nil && wait {
Sietse Ringers's avatar
Sietse Ringers committed
665
		<-ch
666
		// generate yet another one for future calls, but no need to wait now
667
		go client.paillierKeyWorker(false, ch)
Sietse Ringers's avatar
Sietse Ringers committed
668
	}
669
	return client.paillierKeyCache
670
}
Sietse Ringers's avatar
Sietse Ringers committed
671

672
func (client *Client) paillierKeyWorker(wait bool, ch chan bool) {
673
	newkey, _ := paillier.GenerateKey(rand.Reader, 2048)
674
675
	client.paillierKeyCache = (*paillierPrivateKey)(newkey)
	client.storage.StorePaillierKeys(client.paillierKeyCache)
676
677
678
679
680
	if wait {
		ch <- true
	}
}

681
func (client *Client) genSchemeManagersList(enrolled bool) []irma.SchemeManagerIdentifier {
682
	list := []irma.SchemeManagerIdentifier{}
683
	for name, manager := range client.Configuration.SchemeManagers {
684
		if _, contains := client.keyshareServers[name]; manager.Distributed() && contains == enrolled {
Sietse Ringers's avatar
Sietse Ringers committed
685
			list = append(list, manager.Identifier())
Sietse Ringers's avatar
Sietse Ringers committed
686
687
688
689
		}
	}
	return list
}
Sietse Ringers's avatar
Sietse Ringers committed
690

691
692
693
694
func (client *Client) UnenrolledSchemeManagers() []irma.SchemeManagerIdentifier {
	return client.genSchemeManagersList(false)
}

695
func (client *Client) EnrolledSchemeManagers() []irma.SchemeManagerIdentifier {
696
	return client.genSchemeManagersList(true)
697
698
}

699
// KeyshareEnroll attempts to enroll at the keyshare server of the specified scheme manager.
700
func (client *Client) KeyshareEnroll(manager irma.SchemeManagerIdentifier, email *string, pin string, lang string) {
Sietse Ringers's avatar
Sietse Ringers committed
701
	go func() {
702
		err := client.keyshareEnrollWorker(manager, email, pin, lang)
Sietse Ringers's avatar
Sietse Ringers committed
703
		if err != nil {
Tomas's avatar
Tomas committed
704
			client.handler.EnrollmentFailure(manager, err)
Sietse Ringers's avatar
Sietse Ringers committed
705
706
		}
	}()
707
708
}

709
func (client *Client) keyshareEnrollWorker(managerID irma.SchemeManagerIdentifier, email *string, pin string, lang string) error {
710
	manager, ok := client.Configuration.SchemeManagers[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
711
712
713
714
715
716
717
718
719
720
	if !ok {
		return errors.New("Unknown scheme manager")
	}
	if len(manager.KeyshareServer) == 0 {
		return errors.New("Scheme manager has no keyshare server")
	}
	if len(pin) < 5 {
		return errors.New("PIN too short, must be at least 5 characters")
	}

721
	transport := irma.NewHTTPTransport(manager.KeyshareServer)
722
	kss, err := newKeyshareServer(managerID, client.paillierKey(true), manager.KeyshareServer)
Sietse Ringers's avatar
Sietse Ringers committed
723
724
725
	if err != nil {
		return err
	}
726
	message := keyshareEnrollment{
727
		Email:     email,
Sietse Ringers's avatar
Sietse Ringers committed
728
		Pin:       kss.HashedPin(pin),
729
		Language:  lang,
Sietse Ringers's avatar
Sietse Ringers committed
730
731
732
		PublicKey: (*paillierPublicKey)(&kss.PrivateKey.PublicKey),
	}

733
734
	qr := &irma.Qr{}
	err = transport.Post("client/register", qr, message)
Sietse Ringers's avatar
Sietse Ringers committed
735
736
737
738
	if err != nil {
		return err
	}

739
740
741
742
743
	// We add the new keyshare server to the client here, without saving it to disk,
	// and start the issuance session for the keyshare server login attribute -
	// keyshare.go needs the relevant keyshare server to be present in the client.
	// If the session succeeds or fails, the keyshare server is stored to disk or
	// removed from the client by the keyshareEnrollmentHandler.
744
	client.keyshareServers[managerID] = kss
745
746
747
748
749
750
751
	client.NewSession(qr, &keyshareEnrollmentHandler{
		client: client,
		pin:    pin,
		kss:    kss,
	})

	return nil
Sietse Ringers's avatar
Sietse Ringers committed
752
753
}

754
func (client *Client) KeyshareChangePin(manager irma.SchemeManagerIdentifier, oldPin string, newPin string) {
755
	go func() {
756
		err := client.keyshareChangePinWorker(manager, oldPin, newPin)
757
		if err != nil {
758
			client.handler.ChangePinFailure(manager, err)
759
760
761
762
		}
	}()
}

763
func (client *Client) keyshareChangePinWorker(managerID irma.SchemeManagerIdentifier, oldPin string, newPin string) error {
764
765
766
767
768
769
	kss, ok := client.keyshareServers[managerID]
	if !ok {
		return errors.New("Unknown keyshare server")
	}

	transport := irma.NewHTTPTransport(kss.URL)
770
	message := keyshareChangepin{
771
		Username: kss.Username,
772
773
		OldPin: kss.HashedPin(oldPin),
		NewPin: kss.HashedPin(newPin),
774
775
776
777
778
779
780
	}

	res := &keysharePinStatus{}
	err := transport.Post("users/change/pin", res, message)
	if err != nil {
		return err
	}
781

782
	if res.Status != kssPinSuccess {
783
		client.handler.ChangePinIncorrect(managerID)
784
	} else {
785
		client.handler.ChangePinSuccess(managerID)
786
	}
787

788
789
790
	return nil
}

791
// KeyshareRemove unenrolls the keyshare server of the specified scheme manager.
792
func (client *Client) KeyshareRemove(manager irma.SchemeManagerIdentifier) error {
793
	if _, contains := client.keyshareServers[manager]; !contains {
Sietse Ringers's avatar
Sietse Ringers committed
794
795
		return errors.New("Can't uninstall unknown keyshare server")
	}
796
797
	delete(client.keyshareServers, manager)
	return client.storage.StoreKeyshareServers(client.keyshareServers)
Sietse Ringers's avatar
Sietse Ringers committed
798
}
Sietse Ringers's avatar
Sietse Ringers committed
799

Sietse Ringers's avatar
Sietse Ringers committed
800
// KeyshareRemoveAll removes all keyshare server registrations.
801
func (client *Client) KeyshareRemoveAll() error {
802
	client.keyshareServers = map[irma.SchemeManagerIdentifier]*keyshareServer{}
803
	return client.storage.StoreKeyshareServers(client.keyshareServers)
804
805
}

Sietse Ringers's avatar
Sietse Ringers committed
806
807
// Add, load and store log entries

808
809
810
func (client *Client) addLogEntry(entry *LogEntry) error {
	client.logs = append(client.logs, entry)
	return client.storage.StoreLogs(client.logs)
Sietse Ringers's avatar
Sietse Ringers committed
811
812
}

Sietse Ringers's avatar
Sietse Ringers committed
813
// Logs returns the log entries of past events.
814
815
func (client *Client) Logs() ([]*LogEntry, error) {
	if client.logs == nil || len(client.logs) == 0 {
Sietse Ringers's avatar
Sietse Ringers committed
816
		var err error
817
		client.logs, err = client.storage.LoadLogs()
Sietse Ringers's avatar
Sietse Ringers committed
818
819
820
821
		if err != nil {
			return nil, err
		}
	}
822
	return client.logs, nil
Sietse Ringers's avatar
Sietse Ringers committed
823
}
824

825
// SetCrashReportingPreference toggles whether or not crash reports should be sent to Sentry.
Sietse Ringers's avatar
Sietse Ringers committed
826
// Has effect only after restarting.
827
828
829
830
func (client *Client) SetCrashReportingPreference(enable bool) {
	client.Preferences.EnableCrashReporting = enable
	_ = client.storage.StorePreferences(client.Preferences)
	client.applyPreferences()
831
832
}

833
834
func (client *Client) applyPreferences() {
	if client.Preferences.EnableCrashReporting {
835
		raven.SetDSN(SentryDSN)
836
837
	} else {
		raven.SetDSN("")
838
839
	}
}