client.go 26.3 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"
8
	"strconv"
Sietse Ringers's avatar
Sietse Ringers committed
9

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

18
// This file contains most methods of the Client (c.f. session.go
Sietse Ringers's avatar
Sietse Ringers committed
19
20
// and updates.go).
//
Sietse Ringers's avatar
Sietse Ringers committed
21
22
23
24
25
26
27
28
// 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
29
30
31
32
33
34
35
// 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
36
// immediately need to be available anyway.
Sietse Ringers's avatar
Sietse Ringers committed
37
38
39
40
41
//
// - 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).

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

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

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

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

68
69
type Preferences struct {
	EnableCrashReporting bool
70
71
}

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

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

83
84
85
type ChangePinHandler interface {
	ChangePinFailure(manager irma.SchemeManagerIdentifier, err error)
	ChangePinSuccess(manager irma.SchemeManagerIdentifier)
86
87
	ChangePinIncorrect(manager irma.SchemeManagerIdentifier, attempts int)
	ChangePinBlocked(manager irma.SchemeManagerIdentifier, timeout int)
88
89
}

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

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

100
101
102
103
type secretKey struct {
	Key *big.Int
}

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

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

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

144
	schemeMgrErr := cm.Configuration.ParseOrRestoreFolder()
145
146
147
148
149
	// 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
150
	}
151
152

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

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

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

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

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

189
	return cm, schemeMgrErr
190
191
}

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

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

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

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

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

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

	// Append the new cred to our attributes and credentials
234
	client.attributes[id] = append(client.attrs(id), cred.AttributeList())
235
236
237
238
239
240
	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
241
242
	}

243
	if err = client.storage.StoreSignature(cred); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
244
245
246
		return
	}
	if storeAttributes {
247
		err = client.storage.StoreAttributes(client.attributes)
Sietse Ringers's avatar
Sietse Ringers committed
248
249
250
251
252
253
254
255
256
257
258
259
260
261
	}
	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

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

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

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

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

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

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

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

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

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

343
// Attribute and credential getter methods
Sietse Ringers's avatar
Sietse Ringers committed
344

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

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

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

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

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

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

434
	return client.credentials[id][counter], nil
435
436
}

Sietse Ringers's avatar
Sietse Ringers committed
437
// Methods used in the IRMA protocol
438

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

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

	return candidates
}

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

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

	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 {
512
513
			indices := make([]int, 1, 1)
			indices[0] = 1 // Always include metadata
514
515
516
517
518
519
			grouped[ici] = indices
		}

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

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

	return grouped, nil
}

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

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

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

566
567
568
569
570
571
572
573
574
575
	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
	}

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

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

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

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

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

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

627
628
	// 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
629
	gabicreds := []*gabi.Credential{}
Sietse Ringers's avatar
Sietse Ringers committed
630
	for i, sig := range msg {
631
		attrs, err := request.Credentials[i].AttributeList(client.Configuration, getMetadataVersion(request.GetVersion()))
Sietse Ringers's avatar
Sietse Ringers committed
632
633
634
		if err != nil {
			return err
		}
635
		cred, err := client.state.builders[i].ConstructCredential(sig, attrs.Ints)
Sietse Ringers's avatar
Sietse Ringers committed
636
637
638
		if err != nil {
			return err
		}
639
		gabicreds = append(gabicreds, cred)
Sietse Ringers's avatar
Sietse Ringers committed
640
641
	}

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

Sietse Ringers's avatar
Sietse Ringers committed
652
	return nil
Sietse Ringers's avatar
Sietse Ringers committed
653
}
654

Sietse Ringers's avatar
Sietse Ringers committed
655
656
// Keyshare server handling

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

662
663
	// 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
664
	// the if-clause below match.
665
	go client.paillierKeyWorker(cached == nil && wait, ch)
666
	if cached == nil && wait {
Sietse Ringers's avatar
Sietse Ringers committed
667
		<-ch
668
		// generate yet another one for future calls, but no need to wait now
669
		go client.paillierKeyWorker(false, ch)
Sietse Ringers's avatar
Sietse Ringers committed
670
	}
671
	return client.paillierKeyCache
672
}
Sietse Ringers's avatar
Sietse Ringers committed
673

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

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

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

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

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

711
func (client *Client) keyshareEnrollWorker(managerID irma.SchemeManagerIdentifier, email *string, pin string, lang string) error {
712
	manager, ok := client.Configuration.SchemeManagers[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
713
714
715
716
717
718
719
720
721
722
	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")
	}

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

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

741
742
743
744
745
	// 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.
746
	client.keyshareServers[managerID] = kss
747
748
749
750
751
752
753
	client.NewSession(qr, &keyshareEnrollmentHandler{
		client: client,
		pin:    pin,
		kss:    kss,
	})

	return nil
Sietse Ringers's avatar
Sietse Ringers committed
754
755
}

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

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

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

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

784
785
	switch res.Status {
	case kssPinSuccess:
786
		client.handler.ChangePinSuccess(managerID)
787
	case kssPinFailure:
788
789
790
791
792
		attempts, err := strconv.Atoi(res.Message)
		if err != nil {
			return err
		}
		client.handler.ChangePinIncorrect(managerID, attempts)
793
	case kssPinError:
794
795
796
797
798
		timeout, err := strconv.Atoi(res.Message)
		if err != nil {
			return err
		}
		client.handler.ChangePinBlocked(managerID, timeout)
799
800
	default:
		return errors.New("Unknown keyshare response")
801
	}
802

803
804
805
	return nil
}

806
// KeyshareRemove unenrolls the keyshare server of the specified scheme manager.
807
func (client *Client) KeyshareRemove(manager irma.SchemeManagerIdentifier) error {
808
	if _, contains := client.keyshareServers[manager]; !contains {
Sietse Ringers's avatar
Sietse Ringers committed
809
810
		return errors.New("Can't uninstall unknown keyshare server")
	}
811
812
	delete(client.keyshareServers, manager)
	return client.storage.StoreKeyshareServers(client.keyshareServers)
Sietse Ringers's avatar
Sietse Ringers committed
813
}
Sietse Ringers's avatar
Sietse Ringers committed
814

Sietse Ringers's avatar
Sietse Ringers committed
815
// KeyshareRemoveAll removes all keyshare server registrations.
816
func (client *Client) KeyshareRemoveAll() error {
817
	client.keyshareServers = map[irma.SchemeManagerIdentifier]*keyshareServer{}
818
	return client.storage.StoreKeyshareServers(client.keyshareServers)
819
820
}

Sietse Ringers's avatar
Sietse Ringers committed
821
822
// Add, load and store log entries

823
824
825
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
826
827
}

Sietse Ringers's avatar
Sietse Ringers committed
828
// Logs returns the log entries of past events.
829
830
func (client *Client) Logs() ([]*LogEntry, error) {
	if client.logs == nil || len(client.logs) == 0 {
Sietse Ringers's avatar
Sietse Ringers committed
831
		var err error
832
		client.logs, err = client.storage.LoadLogs()
Sietse Ringers's avatar
Sietse Ringers committed
833
834
835
836
		if err != nil {
			return nil, err
		}
	}
837
	return client.logs, nil
Sietse Ringers's avatar
Sietse Ringers committed
838
}
839

840
// SetCrashReportingPreference toggles whether or not crash reports should be sent to Sentry.
Sietse Ringers's avatar
Sietse Ringers committed
841
// Has effect only after restarting.
842
843
844
845
func (client *Client) SetCrashReportingPreference(enable bool) {
	client.Preferences.EnableCrashReporting = enable
	_ = client.storage.StorePreferences(client.Preferences)
	client.applyPreferences()