client.go 23.5 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
	"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
20
21
22
23
24
25
26
// and updates.go).
//
// 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
27
// immediately need to be available anyway.
Sietse Ringers's avatar
Sietse Ringers committed
28
29
30
31
32
//
// - 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).

33
// Client (de)serializes credentials and keyshare server information
Sietse Ringers's avatar
Sietse Ringers committed
34
35
36
37
// 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.
38
type Client struct {
Sietse Ringers's avatar
Sietse Ringers committed
39
	// Stuff we manage on disk
40
	secretkey        *secretKey
41
42
43
	attributes       map[irma.CredentialTypeIdentifier][]*irma.AttributeList
	credentials      map[irma.CredentialTypeIdentifier]map[int]*credential
	keyshareServers  map[irma.SchemeManagerIdentifier]*keyshareServer
44
	paillierKeyCache *paillierPrivateKey
Sietse Ringers's avatar
Sietse Ringers committed
45
	logs             []*LogEntry
Sietse Ringers's avatar
Sietse Ringers committed
46
	updates          []update
47

Sietse Ringers's avatar
Sietse Ringers committed
48
49
50
51
	// Where we store/load it to/from
	storage storage

	// Other state
52
	Preferences              Preferences
53
	Configuration            *irma.Configuration
54
	UnenrolledSchemeManagers []irma.SchemeManagerIdentifier
55
56
57
	irmaConfigurationPath    string
	androidStoragePath       string
	handler                  ClientHandler
58
	state                    *issuanceState
59
60
}

61
62
63
type Preferences struct {
	EnableCrashReporting bool
	SentryDSN            string
64
65
}

66
67
68
var defaultClientConfig = Preferences{
	EnableCrashReporting: true,
	SentryDSN:            "", // Set this in the init() function, empty string -> no crash reports
69
70
}

71
// KeyshareHandler is used for asking the user for his email address and PIN,
72
// for enrolling at a keyshare server.
73
type KeyshareHandler interface {
74
75
	EnrollmentError(manager irma.SchemeManagerIdentifier, err error)
	EnrollmentSuccess(manager irma.SchemeManagerIdentifier)
76
77
}

Sietse Ringers's avatar
Sietse Ringers committed
78
79
// ClientHandler informs the user that the configuration or the list of attributes
// that this client uses has been updated.
80
81
82
type ClientHandler interface {
	KeyshareHandler

83
	UpdateConfiguration(new *irma.IrmaIdentifierSet)
84
	UpdateAttributes()
Sietse Ringers's avatar
Sietse Ringers committed
85
86
}

87
88
89
90
type secretKey struct {
	Key *big.Int
}

91
// New creates a new Client that uses the directory
92
93
94
95
// 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),
96
// and handler is used for informing the user of new stuff, and when a
97
// enrollment to a keyshare server needs to happen.
98
// The client returned by this function has been fully deserialized
99
100
// and is ready for use.
//
Sietse Ringers's avatar
Sietse Ringers committed
101
102
// NOTE: It is the responsibility of the caller that there exists a (properly
// protected) directory at storagePath!
103
func New(
104
105
106
	storagePath string,
	irmaConfigurationPath string,
	androidStoragePath string,
107
	handler ClientHandler,
108
) (*Client, error) {
109
	var err error
110
	if err = fs.AssertPathExists(storagePath); err != nil {
111
112
		return nil, err
	}
113
	if err = fs.AssertPathExists(irmaConfigurationPath); err != nil {
114
115
116
		return nil, err
	}

117
	cm := &Client{
118
119
120
		credentials:           make(map[irma.CredentialTypeIdentifier]map[int]*credential),
		keyshareServers:       make(map[irma.SchemeManagerIdentifier]*keyshareServer),
		attributes:            make(map[irma.CredentialTypeIdentifier][]*irma.AttributeList),
121
122
		irmaConfigurationPath: irmaConfigurationPath,
		androidStoragePath:    androidStoragePath,
123
		handler:               handler,
124
125
	}

126
	cm.Configuration, err = irma.NewConfiguration(storagePath+"/irma_configuration", irmaConfigurationPath)
127
128
129
	if err != nil {
		return nil, err
	}
130
131
132
	err = cm.Configuration.ParseFolder()
	_, isSchemeMgrErr := err.(*irma.SchemeManagerError)
	if err != nil && !isSchemeMgrErr {
133
134
		return nil, err
	}
135
136

	// Ensure storage path exists, and populate it with necessary files
137
	cm.storage = storage{storagePath: storagePath, Configuration: cm.Configuration}
Sietse Ringers's avatar
Sietse Ringers committed
138
	if err = cm.storage.EnsureStorageExists(); err != nil {
139
140
141
		return nil, err
	}

142
	if cm.Preferences, err = cm.storage.LoadClientConfig(); err != nil {
143
144
		return nil, err
	}
145
	cm.applyPreferences()
146

147
	// Perform new update functions from clientUpdates, if any
148
149
150
151
152
	if err = cm.update(); err != nil {
		return nil, err
	}

	// Load our stuff
Sietse Ringers's avatar
Sietse Ringers committed
153
	if cm.secretkey, err = cm.storage.LoadSecretKey(); err != nil {
154
155
		return nil, err
	}
Sietse Ringers's avatar
Sietse Ringers committed
156
	if cm.attributes, err = cm.storage.LoadAttributes(); err != nil {
157
158
		return nil, err
	}
159
	if cm.keyshareServers, err = cm.storage.LoadKeyshareServers(); err != nil {
160
161
		return nil, err
	}
162
	if cm.paillierKeyCache, err = cm.storage.LoadPaillierKeys(); err != nil {
163
164
		return nil, err
	}
165
166
167
	if cm.paillierKeyCache == nil {
		cm.paillierKey(false)
	}
168

169
170
	cm.UnenrolledSchemeManagers = cm.unenrolledSchemeManagers()
	if len(cm.UnenrolledSchemeManagers) > 1 {
171
172
173
174
175
176
		return nil, errors.New("Too many keyshare servers")
	}

	return cm, nil
}

177
// CredentialInfoList returns a list of information of all contained credentials.
178
179
func (client *Client) CredentialInfoList() irma.CredentialInfoList {
	list := irma.CredentialInfoList([]*irma.CredentialInfo{})
180

181
	for _, attrlistlist := range client.attributes {
182
183
		for index, attrlist := range attrlistlist {
			info := attrlist.Info()
184
185
186
			if info == nil {
				continue
			}
187
			info.Index = index
188
			list = append(list, info)
Sietse Ringers's avatar
Sietse Ringers committed
189
190
		}
	}
191

Sietse Ringers's avatar
Sietse Ringers committed
192
193
194
195
	sort.Sort(list)
	return list
}

196
// addCredential adds the specified credential to the Client, saving its signature
Sietse Ringers's avatar
Sietse Ringers committed
197
// imediately, and optionally cm.attributes as well.
198
func (client *Client) addCredential(cred *credential, storeAttributes bool) (err error) {
199
200
201
202
	id := irma.NewCredentialTypeIdentifier("")
	if cred.CredentialType() != nil {
		id = cred.CredentialType().Identifier()
	}
Sietse Ringers's avatar
Sietse Ringers committed
203

204
	// Don't add duplicate creds
205
	for _, attrlistlist := range client.attributes {
206
		for _, attrs := range attrlistlist {
207
			if attrs.Hash() == cred.AttributeList().Hash() {
208
209
210
211
212
213
				return nil
			}
		}
	}

	// If this is a singleton credential type, ensure we have at most one by removing any previous instance
214
	if !id.Empty() && cred.CredentialType().IsSingleton && len(client.creds(id)) > 0 {
215
		client.remove(id, 0, false) // Index is 0, because if we're here we have exactly one
216
217
218
	}

	// Append the new cred to our attributes and credentials
219
	client.attributes[id] = append(client.attrs(id), cred.AttributeList())
220
221
222
223
224
225
	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
226
227
	}

228
	if err = client.storage.StoreSignature(cred); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
229
230
231
		return
	}
	if storeAttributes {
232
		err = client.storage.StoreAttributes(client.attributes)
Sietse Ringers's avatar
Sietse Ringers committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
	}
	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

247
func (client *Client) remove(id irma.CredentialTypeIdentifier, index int, storenow bool) error {
248
	// Remove attributes
249
	list, exists := client.attributes[id]
250
251
252
253
	if !exists || index >= len(list) {
		return errors.Errorf("Can't remove credential %s-%d: no such credential", id.String(), index)
	}
	attrs := list[index]
254
	client.attributes[id] = append(list[:index], list[index+1:]...)
255
	if storenow {
256
		if err := client.storage.StoreAttributes(client.attributes); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
257
258
			return err
		}
259
260
261
	}

	// Remove credential
262
	if creds, exists := client.credentials[id]; exists {
263
		if _, exists := creds[index]; exists {
Sietse Ringers's avatar
Sietse Ringers committed
264
			delete(creds, index)
265
			client.credentials[id] = creds
266
267
268
269
		}
	}

	// Remove signature from storage
270
	if err := client.storage.DeleteSignature(attrs); err != nil {
271
272
273
		return err
	}

274
	removed := map[irma.CredentialTypeIdentifier][]irma.TranslatedString{}
275
276
277
	removed[id] = attrs.Strings()

	if storenow {
278
		return client.addLogEntry(&LogEntry{
279
			Type:    actionRemoval,
280
			Time:    irma.Timestamp(time.Now()),
281
282
283
284
			Removed: removed,
		})
	}
	return nil
285
286
}

Sietse Ringers's avatar
Sietse Ringers committed
287
// RemoveCredential removes the specified credential.
288
func (client *Client) RemoveCredential(id irma.CredentialTypeIdentifier, index int) error {
289
	return client.remove(id, index, true)
290
291
}

Sietse Ringers's avatar
Sietse Ringers committed
292
// RemoveCredentialByHash removes the specified credential.
293
294
func (client *Client) RemoveCredentialByHash(hash string) error {
	cred, index, err := client.credentialByHash(hash)
295
296
297
	if err != nil {
		return err
	}
298
	return client.RemoveCredential(cred.CredentialType().Identifier(), index)
299
300
}

Sietse Ringers's avatar
Sietse Ringers committed
301
// RemoveAllCredentials removes all credentials.
302
func (client *Client) RemoveAllCredentials() error {
303
	removed := map[irma.CredentialTypeIdentifier][]irma.TranslatedString{}
304
	for _, attrlistlist := range client.attributes {
Sietse Ringers's avatar
Sietse Ringers committed
305
306
307
308
		for _, attrs := range attrlistlist {
			if attrs.CredentialType() != nil {
				removed[attrs.CredentialType().Identifier()] = attrs.Strings()
			}
309
			client.storage.DeleteSignature(attrs)
310
311
		}
	}
312
	client.attributes = map[irma.CredentialTypeIdentifier][]*irma.AttributeList{}
313
	if err := client.storage.StoreAttributes(client.attributes); err != nil {
314
315
		return err
	}
316
317
318

	logentry := &LogEntry{
		Type:    actionRemoval,
319
		Time:    irma.Timestamp(time.Now()),
320
321
		Removed: removed,
	}
322
	if err := client.addLogEntry(logentry); err != nil {
323
324
		return err
	}
325
	return client.storage.StoreLogs(client.logs)
326
327
}

328
// Attribute and credential getter methods
Sietse Ringers's avatar
Sietse Ringers committed
329

Sietse Ringers's avatar
Sietse Ringers committed
330
// attrs returns cm.attributes[id], initializing it to an empty slice if neccesary
331
func (client *Client) attrs(id irma.CredentialTypeIdentifier) []*irma.AttributeList {
332
	list, exists := client.attributes[id]
Sietse Ringers's avatar
Sietse Ringers committed
333
	if !exists {
334
		list = make([]*irma.AttributeList, 0, 1)
335
		client.attributes[id] = list
Sietse Ringers's avatar
Sietse Ringers committed
336
337
338
339
340
	}
	return list
}

// creds returns cm.credentials[id], initializing it to an empty map if neccesary
341
func (client *Client) creds(id irma.CredentialTypeIdentifier) map[int]*credential {
342
	list, exists := client.credentials[id]
Sietse Ringers's avatar
Sietse Ringers committed
343
	if !exists {
Sietse Ringers's avatar
Sietse Ringers committed
344
		list = make(map[int]*credential)
345
		client.credentials[id] = list
Sietse Ringers's avatar
Sietse Ringers committed
346
347
348
349
	}
	return list
}

Sietse Ringers's avatar
Sietse Ringers committed
350
// Attributes returns the attribute list of the requested credential, or nil if we do not have it.
351
func (client *Client) Attributes(id irma.CredentialTypeIdentifier, counter int) (attributes *irma.AttributeList) {
352
	list := client.attrs(id)
Sietse Ringers's avatar
Sietse Ringers committed
353
	if len(list) <= counter {
Sietse Ringers's avatar
Sietse Ringers committed
354
355
356
357
358
		return
	}
	return list[counter]
}

359
360
func (client *Client) credentialByHash(hash string) (*credential, int, error) {
	for _, attrlistlist := range client.attributes {
361
		for index, attrs := range attrlistlist {
362
			if attrs.Hash() == hash {
363
				cred, err := client.credential(attrs.CredentialType().Identifier(), index)
364
365
366
367
368
369
370
				return cred, index, err
			}
		}
	}
	return nil, 0, nil
}

371
func (client *Client) credentialByID(id irma.CredentialIdentifier) (*credential, error) {
372
	if _, exists := client.attributes[id.Type]; !exists {
Sietse Ringers's avatar
Sietse Ringers committed
373
374
		return nil, nil
	}
375
	for index, attrs := range client.attributes[id.Type] {
376
		if attrs.Hash() == id.Hash {
377
			return client.credential(attrs.CredentialType().Identifier(), index)
Sietse Ringers's avatar
Sietse Ringers committed
378
379
380
		}
	}
	return nil, nil
381
382
}

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

419
	return client.credentials[id][counter], nil
420
421
}

Sietse Ringers's avatar
Sietse Ringers committed
422
// Methods used in the IRMA protocol
423

424
// Candidates returns a list of attributes present in this client
Sietse Ringers's avatar
Sietse Ringers committed
425
// that satisfy the specified attribute disjunction.
426
427
func (client *Client) Candidates(disjunction *irma.AttributeDisjunction) []*irma.AttributeIdentifier {
	candidates := make([]*irma.AttributeIdentifier, 0, 10)
428
429

	for _, attribute := range disjunction.Attributes {
Sietse Ringers's avatar
Sietse Ringers committed
430
		credID := attribute.CredentialTypeIdentifier()
431
		if !client.Configuration.Contains(credID) {
432
433
			continue
		}
434
		creds := client.attributes[credID]
435
436
437
438
		count := len(creds)
		if count == 0 {
			continue
		}
439
		for _, attrs := range creds {
440
			id := &irma.AttributeIdentifier{Type: attribute, Hash: attrs.Hash()}
441
442
443
			if attribute.IsCredential() {
				candidates = append(candidates, id)
			} else {
444
				val := attrs.UntranslatedAttribute(attribute)
445
				if val == "" { // This won't handle empty attributes correctly
446
447
448
449
450
451
452
453
454
455
456
457
					continue
				}
				if !disjunction.HasValues() || val == disjunction.Values[attribute] {
					candidates = append(candidates, id)
				}
			}
		}
	}

	return candidates
}

458
// CheckSatisfiability checks if this client has the required attributes
Sietse Ringers's avatar
Sietse Ringers committed
459
460
// to satisfy the specifed disjunction list. If not, the unsatisfiable disjunctions
// are returned.
461
func (client *Client) CheckSatisfiability(
462
463
464
465
	disjunctions irma.AttributeDisjunctionList,
) ([][]*irma.AttributeIdentifier, irma.AttributeDisjunctionList) {
	candidates := [][]*irma.AttributeIdentifier{}
	missing := irma.AttributeDisjunctionList{}
466
	for i, disjunction := range disjunctions {
467
		candidates = append(candidates, []*irma.AttributeIdentifier{})
468
		candidates[i] = client.Candidates(disjunction)
469
		if len(candidates[i]) == 0 {
470
471
472
			missing = append(missing, disjunction)
		}
	}
473
	return candidates, missing
474
}
475

476
477
func (client *Client) groupCredentials(choice *irma.DisclosureChoice) (map[irma.CredentialIdentifier][]int, error) {
	grouped := make(map[irma.CredentialIdentifier][]int)
478
479
480
	if choice == nil || choice.Attributes == nil {
		return grouped, nil
	}
481
482
483
484
485
486
487
488

	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 {
489
490
			indices := make([]int, 1, 1)
			indices[0] = 1 // Always include metadata
491
492
493
494
495
496
			grouped[ici] = indices
		}

		if identifier.IsCredential() {
			continue // In this case we only disclose the metadata attribute, which is already handled
		}
497
		index, err := client.Configuration.CredentialTypes[identifier.CredentialTypeIdentifier()].IndexOf(identifier)
498
499
500
501
		if err != nil {
			return nil, err
		}

Sietse Ringers's avatar
Sietse Ringers committed
502
		// These indices will be used in the []*big.Int at gabi.credential.Attributes,
503
		// which doesn't know about the secret key and metadata attribute, so +2
504
		grouped[ici] = append(grouped[ici], index+2)
505
506
507
508
509
	}

	return grouped, nil
}

510
// ProofBuilders constructs a list of proof builders for the specified attribute choice.
511
func (client *Client) ProofBuilders(choice *irma.DisclosureChoice) (gabi.ProofBuilderList, error) {
512
	todisclose, err := client.groupCredentials(choice)
513
514
515
516
	if err != nil {
		return nil, err
	}

517
	builders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
518
	for id, list := range todisclose {
519
		cred, err := client.credentialByID(id)
520
521
522
523
524
		if err != nil {
			return nil, err
		}
		builders = append(builders, cred.Credential.CreateDisclosureProofBuilder(list))
	}
Sietse Ringers's avatar
Sietse Ringers committed
525
	return builders, nil
526
}
Sietse Ringers's avatar
Sietse Ringers committed
527

Sietse Ringers's avatar
Sietse Ringers committed
528
// Proofs computes disclosure proofs containing the attributes specified by choice.
529
func (client *Client) Proofs(choice *irma.DisclosureChoice, request irma.IrmaSession, issig bool) (gabi.ProofList, error) {
530
	builders, err := client.ProofBuilders(choice)
Sietse Ringers's avatar
Sietse Ringers committed
531
532
533
	if err != nil {
		return nil, err
	}
534
	return builders.BuildProofList(request.GetContext(), request.GetNonce(), issig), nil
Sietse Ringers's avatar
Sietse Ringers committed
535
536
}

537
538
// IssuanceProofBuilders constructs a list of proof builders in the issuance protocol
// for the future credentials as well as possibly any disclosed attributes.
539
func (client *Client) IssuanceProofBuilders(request *irma.IssuanceRequest) (gabi.ProofBuilderList, error) {
Sietse Ringers's avatar
Cleanup    
Sietse Ringers committed
540
	state, err := newIssuanceState()
Sietse Ringers's avatar
Sietse Ringers committed
541
542
543
	if err != nil {
		return nil, err
	}
544
	client.state = state
Sietse Ringers's avatar
Sietse Ringers committed
545

546
	proofBuilders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
Sietse Ringers's avatar
Sietse Ringers committed
547
	for _, futurecred := range request.Credentials {
Sietse Ringers's avatar
Sietse Ringers committed
548
		var pk *gabi.PublicKey
549
		pk, err = client.Configuration.PublicKey(futurecred.CredentialTypeID.IssuerIdentifier(), futurecred.KeyCounter)
550
551
552
		if err != nil {
			return nil, err
		}
553
		credBuilder := gabi.NewCredentialBuilder(
554
			pk, request.GetContext(), client.secretkey.Key, state.nonce2)
555
		state.builders = append(state.builders, credBuilder)
Sietse Ringers's avatar
Sietse Ringers committed
556
557
		proofBuilders = append(proofBuilders, credBuilder)
	}
Sietse Ringers's avatar
Sietse Ringers committed
558

559
	disclosures, err := client.ProofBuilders(request.Choice)
Sietse Ringers's avatar
Sietse Ringers committed
560
561
562
	if err != nil {
		return nil, err
	}
Sietse Ringers's avatar
Sietse Ringers committed
563
	proofBuilders = append(disclosures, proofBuilders...)
Sietse Ringers's avatar
Sietse Ringers committed
564
565
	return proofBuilders, nil
}
Sietse Ringers's avatar
Sietse Ringers committed
566

Sietse Ringers's avatar
Sietse Ringers committed
567
568
// IssueCommitments computes issuance commitments, along with disclosure proofs
// specified by choice.
569
func (client *Client) IssueCommitments(request *irma.IssuanceRequest) (*gabi.IssueCommitmentMessage, error) {
570
	proofBuilders, err := client.IssuanceProofBuilders(request)
Sietse Ringers's avatar
Sietse Ringers committed
571
572
573
	if err != nil {
		return nil, err
	}
574
	list := proofBuilders.BuildProofList(request.GetContext(), request.GetNonce(), false)
575
	return &gabi.IssueCommitmentMessage{Proofs: list, Nonce2: client.state.nonce2}, nil
Sietse Ringers's avatar
Sietse Ringers committed
576
577
}

Sietse Ringers's avatar
Sietse Ringers committed
578
579
// ConstructCredentials constructs and saves new credentials
// using the specified issuance signature messages.
580
func (client *Client) ConstructCredentials(msg []*gabi.IssueSignatureMessage, request *irma.IssuanceRequest) error {
581
	if len(msg) != len(client.state.builders) {
Sietse Ringers's avatar
Sietse Ringers committed
582
583
584
		return errors.New("Received unexpected amount of signatures")
	}

585
586
	// 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
587
	gabicreds := []*gabi.Credential{}
Sietse Ringers's avatar
Sietse Ringers committed
588
	for i, sig := range msg {
589
		attrs, err := request.Credentials[i].AttributeList(client.Configuration)
Sietse Ringers's avatar
Sietse Ringers committed
590
591
592
		if err != nil {
			return err
		}
593
		cred, err := client.state.builders[i].ConstructCredential(sig, attrs.Ints)
Sietse Ringers's avatar
Sietse Ringers committed
594
595
596
		if err != nil {
			return err
		}
597
		gabicreds = append(gabicreds, cred)
Sietse Ringers's avatar
Sietse Ringers committed
598
599
	}

600
	for _, gabicred := range gabicreds {
601
		newcred, err := newCredential(gabicred, client.Configuration)
602
603
604
		if err != nil {
			return err
		}
605
		if err = client.addCredential(newcred, true); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
606
607
			return err
		}
Sietse Ringers's avatar
Sietse Ringers committed
608
	}
609

Sietse Ringers's avatar
Sietse Ringers committed
610
	return nil
Sietse Ringers's avatar
Sietse Ringers committed
611
}
612

Sietse Ringers's avatar
Sietse Ringers committed
613
614
// Keyshare server handling

615
// PaillierKey returns a new Paillier key (and generates a new one in a goroutine).
616
617
func (client *Client) paillierKey(wait bool) *paillierPrivateKey {
	cached := client.paillierKeyCache
Sietse Ringers's avatar
Sietse Ringers committed
618
	ch := make(chan bool)
619

620
621
	// 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
622
	// the if-clause below match.
623
	go client.paillierKeyWorker(cached == nil && wait, ch)
624
	if cached == nil && wait {
Sietse Ringers's avatar
Sietse Ringers committed
625
		<-ch
626
		// generate yet another one for future calls, but no need to wait now
627
		go client.paillierKeyWorker(false, ch)
Sietse Ringers's avatar
Sietse Ringers committed
628
	}
629
	return client.paillierKeyCache
630
}
Sietse Ringers's avatar
Sietse Ringers committed
631

632
func (client *Client) paillierKeyWorker(wait bool, ch chan bool) {
633
	newkey, _ := paillier.GenerateKey(rand.Reader, 2048)
634
635
	client.paillierKeyCache = (*paillierPrivateKey)(newkey)
	client.storage.StorePaillierKeys(client.paillierKeyCache)
636
637
638
639
640
	if wait {
		ch <- true
	}
}

641
642
func (client *Client) unenrolledSchemeManagers() []irma.SchemeManagerIdentifier {
	list := []irma.SchemeManagerIdentifier{}
643
	for name, manager := range client.Configuration.SchemeManagers {
644
		if _, contains := client.keyshareServers[name]; manager.Distributed() && !contains {
Sietse Ringers's avatar
Sietse Ringers committed
645
			list = append(list, manager.Identifier())
Sietse Ringers's avatar
Sietse Ringers committed
646
647
648
649
		}
	}
	return list
}
Sietse Ringers's avatar
Sietse Ringers committed
650

651
// KeyshareEnroll attempts to enroll at the keyshare server of the specified scheme manager.
652
func (client *Client) KeyshareEnroll(manager irma.SchemeManagerIdentifier, email, pin string) {
Sietse Ringers's avatar
Sietse Ringers committed
653
	go func() {
654
		defer func() {
655
			if e := recover(); e != nil {
656
				if client.handler != nil {
657
					client.handler.EnrollmentError(manager, panicToError(e))
658
				}
659
			}
660
661
		}()

662
663
		err := client.keyshareEnrollWorker(manager, email, pin)
		client.UnenrolledSchemeManagers = client.unenrolledSchemeManagers()
Sietse Ringers's avatar
Sietse Ringers committed
664
		if err != nil {
665
			client.handler.EnrollmentError(manager, err)
Sietse Ringers's avatar
Sietse Ringers committed
666
		} else {
667
			client.handler.EnrollmentSuccess(manager)
Sietse Ringers's avatar
Sietse Ringers committed
668
669
		}
	}()
670

671
672
}

673
func (client *Client) keyshareEnrollWorker(managerID irma.SchemeManagerIdentifier, email, pin string) error {
674
	manager, ok := client.Configuration.SchemeManagers[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
675
676
677
678
679
680
681
682
683
684
	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")
	}

685
	transport := irma.NewHTTPTransport(manager.KeyshareServer)
686
	kss, err := newKeyshareServer(client.paillierKey(true), manager.KeyshareServer, email)
Sietse Ringers's avatar
Sietse Ringers committed
687
688
689
	if err != nil {
		return err
	}
690
	message := keyshareEnrollment{
Sietse Ringers's avatar
Sietse Ringers committed
691
692
693
694
695
696
697
698
699
700
701
		Username:  email,
		Pin:       kss.HashedPin(pin),
		PublicKey: (*paillierPublicKey)(&kss.PrivateKey.PublicKey),
	}

	result := &struct{}{}
	err = transport.Post("web/users/selfenroll", result, message)
	if err != nil {
		return err
	}

702
703
	client.keyshareServers[managerID] = kss
	return client.storage.StoreKeyshareServers(client.keyshareServers)
Sietse Ringers's avatar
Sietse Ringers committed
704
705
}

706
// KeyshareRemove unenrolls the keyshare server of the specified scheme manager.
707
func (client *Client) KeyshareRemove(manager irma.SchemeManagerIdentifier) error {
708
	if _, contains := client.keyshareServers[manager]; !contains {
Sietse Ringers's avatar
Sietse Ringers committed
709
710
		return errors.New("Can't uninstall unknown keyshare server")
	}
711
712
	delete(client.keyshareServers, manager)
	return client.storage.StoreKeyshareServers(client.keyshareServers)
Sietse Ringers's avatar
Sietse Ringers committed
713
}
Sietse Ringers's avatar
Sietse Ringers committed
714

Sietse Ringers's avatar
Sietse Ringers committed
715
// KeyshareRemoveAll removes all keyshare server registrations.
716
func (client *Client) KeyshareRemoveAll() error {
717
	client.keyshareServers = map[irma.SchemeManagerIdentifier]*keyshareServer{}
718
719
	client.UnenrolledSchemeManagers = client.unenrolledSchemeManagers()
	return client.storage.StoreKeyshareServers(client.keyshareServers)
720
721
}

Sietse Ringers's avatar
Sietse Ringers committed
722
723
// Add, load and store log entries

724
725
726
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
727
728
}

Sietse Ringers's avatar
Sietse Ringers committed
729
// Logs returns the log entries of past events.
730
731
func (client *Client) Logs() ([]*LogEntry, error) {
	if client.logs == nil || len(client.logs) == 0 {
Sietse Ringers's avatar
Sietse Ringers committed
732
		var err error
733
		client.logs, err = client.storage.LoadLogs()
Sietse Ringers's avatar
Sietse Ringers committed
734
735
736
737
		if err != nil {
			return nil, err
		}
	}
738
	return client.logs, nil
Sietse Ringers's avatar
Sietse Ringers committed
739
}
740

Sietse Ringers's avatar
Sietse Ringers committed
741
742
// SendCrashReports toggles whether or not crash reports should be sent to Sentry.
// Has effect only after restarting.
743
744
745
746
func (client *Client) SetCrashReportingPreference(enable bool) {
	client.Preferences.EnableCrashReporting = enable
	_ = client.storage.StorePreferences(client.Preferences)
	client.applyPreferences()
747
748
}

749
750
751
752
753
func (client *Client) applyPreferences() {
	if client.Preferences.EnableCrashReporting {
		raven.SetDSN(client.Preferences.SentryDSN)
	} else {
		raven.SetDSN("")
754
755
	}
}