client.go 23.6 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
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
64
// SentryDSN should be set in the init() function
// Setting it to an empty string means no crash reports
var SentryDSN = ""

65
66
type Preferences struct {
	EnableCrashReporting bool
67
68
}

69
var defaultPreferences = Preferences{
70
	EnableCrashReporting: true,
71
72
}

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

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

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

89
90
91
92
type secretKey struct {
	Key *big.Int
}

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

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

128
	cm.Configuration, err = irma.NewConfiguration(storagePath+"/irma_configuration", irmaConfigurationPath)
129
130
131
	if err != nil {
		return nil, err
	}
132

133
	schemeMgrErr := cm.Configuration.ParseOrRestoreFolder()
134
135
136
137
138
	// 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
139
	}
140
141

	// Ensure storage path exists, and populate it with necessary files
142
	cm.storage = storage{storagePath: storagePath, Configuration: cm.Configuration}
Sietse Ringers's avatar
Sietse Ringers committed
143
	if err = cm.storage.EnsureStorageExists(); err != nil {
144
145
146
		return nil, err
	}

147
	if cm.Preferences, err = cm.storage.LoadPreferences(); err != nil {
148
149
		return nil, err
	}
150
	cm.applyPreferences()
151

152
	// Perform new update functions from clientUpdates, if any
153
154
155
156
157
	if err = cm.update(); err != nil {
		return nil, err
	}

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

174
175
	cm.UnenrolledSchemeManagers = cm.unenrolledSchemeManagers()
	if len(cm.UnenrolledSchemeManagers) > 1 {
176
177
178
		return nil, errors.New("Too many keyshare servers")
	}

179
	return cm, schemeMgrErr
180
181
}

182
// CredentialInfoList returns a list of information of all contained credentials.
183
184
func (client *Client) CredentialInfoList() irma.CredentialInfoList {
	list := irma.CredentialInfoList([]*irma.CredentialInfo{})
185

186
	for _, attrlistlist := range client.attributes {
187
188
		for index, attrlist := range attrlistlist {
			info := attrlist.Info()
189
190
191
			if info == nil {
				continue
			}
192
			info.Index = index
193
			list = append(list, info)
Sietse Ringers's avatar
Sietse Ringers committed
194
195
		}
	}
196

Sietse Ringers's avatar
Sietse Ringers committed
197
198
199
200
	sort.Sort(list)
	return list
}

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

209
	// Don't add duplicate creds
210
	for _, attrlistlist := range client.attributes {
211
		for _, attrs := range attrlistlist {
212
			if attrs.Hash() == cred.AttributeList().Hash() {
213
214
215
216
217
218
				return nil
			}
		}
	}

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

	// Append the new cred to our attributes and credentials
224
	client.attributes[id] = append(client.attrs(id), cred.AttributeList())
225
226
227
228
229
230
	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
231
232
	}

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

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

	// Remove credential
267
	if creds, exists := client.credentials[id]; exists {
268
		if _, exists := creds[index]; exists {
Sietse Ringers's avatar
Sietse Ringers committed
269
			delete(creds, index)
270
			client.credentials[id] = creds
271
272
273
274
		}
	}

	// Remove signature from storage
275
	if err := client.storage.DeleteSignature(attrs); err != nil {
276
277
278
		return err
	}

279
	removed := map[irma.CredentialTypeIdentifier][]irma.TranslatedString{}
280
281
282
	removed[id] = attrs.Strings()

	if storenow {
283
		return client.addLogEntry(&LogEntry{
284
			Type:    actionRemoval,
285
			Time:    irma.Timestamp(time.Now()),
286
287
288
289
			Removed: removed,
		})
	}
	return nil
290
291
}

Sietse Ringers's avatar
Sietse Ringers committed
292
// RemoveCredential removes the specified credential.
293
func (client *Client) RemoveCredential(id irma.CredentialTypeIdentifier, index int) error {
294
	return client.remove(id, index, true)
295
296
}

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

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

	logentry := &LogEntry{
		Type:    actionRemoval,
324
		Time:    irma.Timestamp(time.Now()),
325
326
		Removed: removed,
	}
327
	if err := client.addLogEntry(logentry); err != nil {
328
329
		return err
	}
330
	return client.storage.StoreLogs(client.logs)
331
332
}

333
// Attribute and credential getter methods
Sietse Ringers's avatar
Sietse Ringers committed
334

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

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

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

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

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

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

424
	return client.credentials[id][counter], nil
425
426
}

Sietse Ringers's avatar
Sietse Ringers committed
427
// Methods used in the IRMA protocol
428

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

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

	return candidates
}

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

481
482
func (client *Client) groupCredentials(choice *irma.DisclosureChoice) (map[irma.CredentialIdentifier][]int, error) {
	grouped := make(map[irma.CredentialIdentifier][]int)
483
484
485
	if choice == nil || choice.Attributes == nil {
		return grouped, nil
	}
486
487
488
489
490
491
492
493

	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 {
494
495
			indices := make([]int, 1, 1)
			indices[0] = 1 // Always include metadata
496
497
498
499
500
501
			grouped[ici] = indices
		}

		if identifier.IsCredential() {
			continue // In this case we only disclose the metadata attribute, which is already handled
		}
502
		index, err := client.Configuration.CredentialTypes[identifier.CredentialTypeIdentifier()].IndexOf(identifier)
503
504
505
506
		if err != nil {
			return nil, err
		}

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

	return grouped, nil
}

515
// ProofBuilders constructs a list of proof builders for the specified attribute choice.
516
func (client *Client) ProofBuilders(choice *irma.DisclosureChoice) (gabi.ProofBuilderList, error) {
517
	todisclose, err := client.groupCredentials(choice)
518
519
520
521
	if err != nil {
		return nil, err
	}

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

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

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

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

564
	disclosures, err := client.ProofBuilders(request.Choice)
Sietse Ringers's avatar
Sietse Ringers committed
565
566
567
	if err != nil {
		return nil, err
	}
Sietse Ringers's avatar
Sietse Ringers committed
568
	proofBuilders = append(disclosures, proofBuilders...)
Sietse Ringers's avatar
Sietse Ringers committed
569
570
	return proofBuilders, nil
}
Sietse Ringers's avatar
Sietse Ringers committed
571

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

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

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

605
	for _, gabicred := range gabicreds {
606
		newcred, err := newCredential(gabicred, client.Configuration)
607
608
609
		if err != nil {
			return err
		}
610
		if err = client.addCredential(newcred, true); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
611
612
			return err
		}
Sietse Ringers's avatar
Sietse Ringers committed
613
	}
614

Sietse Ringers's avatar
Sietse Ringers committed
615
	return nil
Sietse Ringers's avatar
Sietse Ringers committed
616
}
617

Sietse Ringers's avatar
Sietse Ringers committed
618
619
// Keyshare server handling

620
// PaillierKey returns a new Paillier key (and generates a new one in a goroutine).
621
622
func (client *Client) paillierKey(wait bool) *paillierPrivateKey {
	cached := client.paillierKeyCache
Sietse Ringers's avatar
Sietse Ringers committed
623
	ch := make(chan bool)
624

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

637
func (client *Client) paillierKeyWorker(wait bool, ch chan bool) {
638
	newkey, _ := paillier.GenerateKey(rand.Reader, 2048)
639
640
	client.paillierKeyCache = (*paillierPrivateKey)(newkey)
	client.storage.StorePaillierKeys(client.paillierKeyCache)
641
642
643
644
645
	if wait {
		ch <- true
	}
}

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

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

667
668
		err := client.keyshareEnrollWorker(manager, email, pin)
		client.UnenrolledSchemeManagers = client.unenrolledSchemeManagers()
Sietse Ringers's avatar
Sietse Ringers committed
669
		if err != nil {
670
			client.handler.EnrollmentError(manager, err)
Sietse Ringers's avatar
Sietse Ringers committed
671
		} else {
672
			client.handler.EnrollmentSuccess(manager)
Sietse Ringers's avatar
Sietse Ringers committed
673
674
		}
	}()
675

676
677
}

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

690
	transport := irma.NewHTTPTransport(manager.KeyshareServer)
691
	kss, err := newKeyshareServer(managerID, client.paillierKey(true), manager.KeyshareServer, email)
Sietse Ringers's avatar
Sietse Ringers committed
692
693
694
	if err != nil {
		return err
	}
695
	message := keyshareEnrollment{
Sietse Ringers's avatar
Sietse Ringers committed
696
697
698
699
700
701
702
703
704
705
706
		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
	}

707
708
	client.keyshareServers[managerID] = kss
	return client.storage.StoreKeyshareServers(client.keyshareServers)
Sietse Ringers's avatar
Sietse Ringers committed
709
710
}

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

Sietse Ringers's avatar
Sietse Ringers committed
720
// KeyshareRemoveAll removes all keyshare server registrations.
721
func (client *Client) KeyshareRemoveAll() error {
722
	client.keyshareServers = map[irma.SchemeManagerIdentifier]*keyshareServer{}
723
724
	client.UnenrolledSchemeManagers = client.unenrolledSchemeManagers()
	return client.storage.StoreKeyshareServers(client.keyshareServers)
725
726
}

Sietse Ringers's avatar
Sietse Ringers committed
727
728
// Add, load and store log entries

729
730
731
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
732
733
}

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

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

754
755
func (client *Client) applyPreferences() {
	if client.Preferences.EnableCrashReporting {
756
		raven.SetDSN(SentryDSN)
757
758
	} else {
		raven.SetDSN("")
759
760
	}
}