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

import (
4
	"crypto/rand"
Sietse Ringers's avatar
Sietse Ringers committed
5
	"sort"
6
	"strconv"
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
13
	"github.com/privacybydesign/gabi"
	"github.com/privacybydesign/gabi/big"
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
	attributes       map[irma.CredentialTypeIdentifier][]*irma.AttributeList
46
	credentialsCache map[irma.CredentialTypeIdentifier]map[int]*credential
47
	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
57
58
59
60
	Preferences           Preferences
	Configuration         *irma.Configuration
	irmaConfigurationPath string
	androidStoragePath    string
	handler               ClientHandler
61
62
}

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

67
68
type Preferences struct {
	EnableCrashReporting bool
69
70
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

188
	return cm, schemeMgrErr
189
190
}

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

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

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

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

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

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

	// Append the new cred to our attributes and credentials
234
	client.attributes[id] = append(client.attrs(id), cred.AttributeList())
235
	if !id.Empty() {
236
237
		if _, exists := client.credentialsCache[id]; !exists {
			client.credentialsCache[id] = make(map[int]*credential)
238
239
		}
		counter := len(client.attributes[id]) - 1
240
		client.credentialsCache[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.credentialsCache[id]; exists {
278
		if _, exists := creds[index]; exists {
Sietse Ringers's avatar
Sietse Ringers committed
279
			delete(creds, index)
280
			client.credentialsCache[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.credentialsCache[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.credentialsCache[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.credentialsCache[id][counter] = cred
Sietse Ringers's avatar
Sietse Ringers committed
432
433
	}

434
	return client.credentialsCache[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
501
func (client *Client) groupCredentials(choice *irma.DisclosureChoice, disjunctions irma.AttributeDisjunctionList) (
	map[irma.CredentialIdentifier][]int, irma.DisclosedAttributeIndices, error,
) {
502
	grouped := make(map[irma.CredentialIdentifier][]int)
503
	if choice == nil || choice.Attributes == nil {
504
		return grouped, irma.DisclosedAttributeIndices{}, nil
505
	}
506

507
508
	attributeIndices := make(irma.DisclosedAttributeIndices, len(choice.Attributes))
	for i, attribute := range choice.Attributes {
509
510
511
512
513
514
		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 {
515
516
			indices := make([]int, 1, 1)
			indices[0] = 1 // Always include metadata
517
518
519
520
			grouped[ici] = indices
		}

		if identifier.IsCredential() {
521
522
523
			attributeIndices[i] = []*irma.DisclosedAttributeIndex{
				{AttributeIndex: 1, Identifier: ici},
			}
524
525
			continue // In this case we only disclose the metadata attribute, which is already handled
		}
526
		index, err := client.Configuration.CredentialTypes[identifier.CredentialTypeIdentifier()].IndexOf(identifier)
527
		if err != nil {
528
529
530
531
532
			return nil, nil, err
		}

		attributeIndices[i] = []*irma.DisclosedAttributeIndex{
			{AttributeIndex: index + 2, Identifier: ici},
533
534
		}

Sietse Ringers's avatar
Sietse Ringers committed
535
		// These indices will be used in the []*big.Int at gabi.credential.Attributes,
536
		// which doesn't know about the secret key and metadata attribute, so +2
537
		grouped[ici] = append(grouped[ici], index+2)
538
539
	}

540
	return grouped, attributeIndices, nil
541
542
}

543
// ProofBuilders constructs a list of proof builders for the specified attribute choice.
544
545
546
func (client *Client) ProofBuilders(choice *irma.DisclosureChoice, request irma.SessionRequest, issig bool,
) (gabi.ProofBuilderList, irma.DisclosedAttributeIndices, error) {
	todisclose, disjunctionChoices, err := client.groupCredentials(choice, request.ToDisclose())
547
	if err != nil {
548
		return nil, nil, err
549
550
	}

551
	builders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
552
553
554

	for i, choice := range disjunctionChoices {
		cred, err := client.credentialByID(choice[0].Identifier)
555
		if err != nil {
556
			return nil, nil, err
557
		}
558
559
		choice[0].CredentialIndex = i
		builders = append(builders, cred.Credential.CreateDisclosureProofBuilder(todisclose[choice[0].Identifier]))
560
	}
561
562
563
564
565
566
567
568
569
570
571
572
573
574

	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 {
575
			return nil, nil, err
576
577
578
		}
	}

579
	return builders, disjunctionChoices, nil
580
581
582
}

// Proofs computes disclosure proofs containing the attributes specified by choice.
583
584
func (client *Client) Proofs(choice *irma.DisclosureChoice, request irma.SessionRequest, issig bool) (*irma.Disclosure, error) {
	builders, choices, err := client.ProofBuilders(choice, request, issig)
585
586
587
588
	if err != nil {
		return nil, err
	}

589
590
591
592
	return &irma.Disclosure{
		Proofs:  builders.BuildProofList(request.GetContext(), request.GetNonce(), issig),
		Indices: choices,
	}, nil
Sietse Ringers's avatar
Sietse Ringers committed
593
594
}

595
596
597
598
599
// generateIssuerProofNonce generates a nonce which the issuer must use in its gabi.ProofS.
func generateIssuerProofNonce() (*big.Int, error) {
	return gabi.RandomBigInt(gabi.DefaultSystemParameters[4096].Lstatzk)
}

600
// IssuanceProofBuilders constructs a list of proof builders in the issuance protocol
601
602
// for the future credentials as well as possibly any disclosed attributes, and generates
// a nonce against which the issuer's proof of knowledge must verify.
603
604
func (client *Client) IssuanceProofBuilders(request *irma.IssuanceRequest,
) (gabi.ProofBuilderList, irma.DisclosedAttributeIndices, *big.Int, error) {
605
	issuerProofNonce, err := generateIssuerProofNonce()
Sietse Ringers's avatar
Sietse Ringers committed
606
	if err != nil {
607
		return nil, nil, nil, err
Sietse Ringers's avatar
Sietse Ringers committed
608
	}
609
	builders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
Sietse Ringers's avatar
Sietse Ringers committed
610
	for _, futurecred := range request.Credentials {
Sietse Ringers's avatar
Sietse Ringers committed
611
		var pk *gabi.PublicKey
612
		pk, err = client.Configuration.PublicKey(futurecred.CredentialTypeID.IssuerIdentifier(), futurecred.KeyCounter)
613
		if err != nil {
614
			return nil, nil, nil, err
615
		}
616
		credBuilder := gabi.NewCredentialBuilder(
617
618
			pk, request.GetContext(), client.secretkey.Key, issuerProofNonce)
		builders = append(builders, credBuilder)
Sietse Ringers's avatar
Sietse Ringers committed
619
	}
Sietse Ringers's avatar
Sietse Ringers committed
620

621
	disclosures, choices, err := client.ProofBuilders(request.Choice, request, false)
Sietse Ringers's avatar
Sietse Ringers committed
622
	if err != nil {
623
		return nil, nil, nil, err
Sietse Ringers's avatar
Sietse Ringers committed
624
	}
625
	builders = append(disclosures, builders...)
626
	return builders, choices, issuerProofNonce, nil
Sietse Ringers's avatar
Sietse Ringers committed
627
}
Sietse Ringers's avatar
Sietse Ringers committed
628

629
630
// IssueCommitments computes issuance commitments, along with disclosure proofs specified by choice,
// and also returns the credential builders which will become the new credentials upon combination with the issuer's signature.
631
632
633
func (client *Client) IssueCommitments(request *irma.IssuanceRequest,
) (*irma.IssueCommitmentMessage, gabi.ProofBuilderList, error) {
	builders, choices, issuerProofNonce, err := client.IssuanceProofBuilders(request)
Sietse Ringers's avatar
Sietse Ringers committed
634
	if err != nil {
635
		return nil, nil, err
Sietse Ringers's avatar
Sietse Ringers committed
636
	}
637
638
639
640
641
642
643
	return &irma.IssueCommitmentMessage{
		IssueCommitmentMessage: &gabi.IssueCommitmentMessage{
			Proofs: builders.BuildProofList(request.GetContext(), request.GetNonce(), false),
			Nonce2: issuerProofNonce,
		},
		Indices: choices,
	}, builders, nil
Sietse Ringers's avatar
Sietse Ringers committed
644
645
}

646
647
648
649
// ConstructCredentials constructs and saves new credentials using the specified issuance signature messages
// and credential builders.
func (client *Client) ConstructCredentials(msg []*gabi.IssueSignatureMessage, request *irma.IssuanceRequest, builders gabi.ProofBuilderList) error {
	if len(msg) > len(builders) {
Sietse Ringers's avatar
Sietse Ringers committed
650
651
652
		return errors.New("Received unexpected amount of signatures")
	}

653
654
	// 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
655
	gabicreds := []*gabi.Credential{}
656
657
658
659
660
661
662
663
664
	offset := 0
	for i, builder := range builders {
		credbuilder, ok := builder.(*gabi.CredentialBuilder)
		if !ok { // Skip builders of disclosure proofs
			offset++
			continue
		}
		sig := msg[i-offset]
		attrs, err := request.Credentials[i-offset].AttributeList(client.Configuration, irma.GetMetadataVersion(request.GetVersion()))
Sietse Ringers's avatar
Sietse Ringers committed
665
666
667
		if err != nil {
			return err
		}
668
		cred, err := credbuilder.ConstructCredential(sig, attrs.Ints)
Sietse Ringers's avatar
Sietse Ringers committed
669
670
671
		if err != nil {
			return err
		}
672
		gabicreds = append(gabicreds, cred)
Sietse Ringers's avatar
Sietse Ringers committed
673
674
	}

675
	for _, gabicred := range gabicreds {
676
		newcred, err := newCredential(gabicred, client.Configuration)
677
678
679
		if err != nil {
			return err
		}
680
		if err = client.addCredential(newcred, true); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
681
682
			return err
		}
Sietse Ringers's avatar
Sietse Ringers committed
683
	}
684

Sietse Ringers's avatar
Sietse Ringers committed
685
	return nil
Sietse Ringers's avatar
Sietse Ringers committed
686
}
687

Sietse Ringers's avatar
Sietse Ringers committed
688
689
// Keyshare server handling

690
// PaillierKey returns a new Paillier key (and generates a new one in a goroutine).
691
692
func (client *Client) paillierKey(wait bool) *paillierPrivateKey {
	cached := client.paillierKeyCache
Sietse Ringers's avatar
Sietse Ringers committed
693
	ch := make(chan bool)
694

695
696
	// 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
697
	// the if-clause below match.
698
	go client.paillierKeyWorker(cached == nil && wait, ch)
699
	if cached == nil && wait {
Sietse Ringers's avatar
Sietse Ringers committed
700
		<-ch
701
		// generate yet another one for future calls, but no need to wait now
702
		go client.paillierKeyWorker(false, ch)
Sietse Ringers's avatar
Sietse Ringers committed
703
	}
704
	return client.paillierKeyCache
705
}
Sietse Ringers's avatar
Sietse Ringers committed
706

707
func (client *Client) paillierKeyWorker(wait bool, ch chan bool) {
708
	newkey, _ := paillier.GenerateKey(rand.Reader, 2048)
709
710
	client.paillierKeyCache = (*paillierPrivateKey)(newkey)
	client.storage.StorePaillierKeys(client.paillierKeyCache)
711
712
713
714
715
	if wait {
		ch <- true
	}
}

716
func (client *Client) genSchemeManagersList(enrolled bool) []irma.SchemeManagerIdentifier {
717
	list := []irma.SchemeManagerIdentifier{}
718
	for name, manager := range client.Configuration.SchemeManagers {
719
		if _, contains := client.keyshareServers[name]; manager.Distributed() && contains == enrolled {
Sietse Ringers's avatar
Sietse Ringers committed
720
			list = append(list, manager.Identifier())
Sietse Ringers's avatar
Sietse Ringers committed
721
722
723
724
		}
	}
	return list
}
Sietse Ringers's avatar
Sietse Ringers committed
725

726
727
728
729
func (client *Client) UnenrolledSchemeManagers() []irma.SchemeManagerIdentifier {
	return client.genSchemeManagersList(false)
}

730
func (client *Client) EnrolledSchemeManagers() []irma.SchemeManagerIdentifier {
731
	return client.genSchemeManagersList(true)
732
733
}

734
// KeyshareEnroll attempts to enroll at the keyshare server of the specified scheme manager.
735
func (client *Client) KeyshareEnroll(manager irma.SchemeManagerIdentifier, email *string, pin string, lang string) {
Sietse Ringers's avatar
Sietse Ringers committed
736
	go func() {
737
		err := client.keyshareEnrollWorker(manager, email, pin, lang)
Sietse Ringers's avatar
Sietse Ringers committed
738
		if err != nil {
Tomas's avatar
Tomas committed
739
			client.handler.EnrollmentFailure(manager, err)
Sietse Ringers's avatar
Sietse Ringers committed
740
741
		}
	}()
742
743
}

744
func (client *Client) keyshareEnrollWorker(managerID irma.SchemeManagerIdentifier, email *string, pin string, lang string) error {
745
	manager, ok := client.Configuration.SchemeManagers[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
746
747
748
749
750
751
752
753
754
755
	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")
	}

756
	transport := irma.NewHTTPTransport(manager.KeyshareServer)
757
	kss, err := newKeyshareServer(managerID, client.paillierKey(true), manager.KeyshareServer)
Sietse Ringers's avatar
Sietse Ringers committed
758
759
760
	if err != nil {
		return err
	}
761
	message := keyshareEnrollment{
762
		Email:     email,
Sietse Ringers's avatar
Sietse Ringers committed
763
		Pin:       kss.HashedPin(pin),
764
		Language:  lang,
Sietse Ringers's avatar
Sietse Ringers committed
765
766
767
		PublicKey: (*paillierPublicKey)(&kss.PrivateKey.PublicKey),
	}

768
769
	qr := &irma.Qr{}
	err = transport.Post("client/register", qr, message)
Sietse Ringers's avatar
Sietse Ringers committed
770
771
772
773
	if err != nil {
		return err
	}

774
775
776
777
778
	// 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.
779
	client.keyshareServers[managerID] = kss
780
	client.newQrSession(qr, &keyshareEnrollmentHandler{
781
782
783
784
785
786
		client: client,
		pin:    pin,
		kss:    kss,
	})

	return nil
Sietse Ringers's avatar
Sietse Ringers committed
787
788
}

789
func (client *Client) KeyshareChangePin(manager irma.SchemeManagerIdentifier, oldPin string, newPin string) {
790
	go func() {
791
		err := client.keyshareChangePinWorker(manager, oldPin, newPin)
792
		if err != nil {
793
			client.handler.ChangePinFailure(manager, err)
794
795
796
797
		}
	}()
}

798
func (client *Client) keyshareChangePinWorker(managerID irma.SchemeManagerIdentifier, oldPin string, newPin string) error {
799
800
801
802
803
804
	kss, ok := client.keyshareServers[managerID]
	if !ok {
		return errors.New("Unknown keyshare server")
	}

	transport := irma.NewHTTPTransport(kss.URL)
805
	message := keyshareChangepin{
806
		Username: kss.Username,
807
808
		OldPin:   kss.HashedPin(oldPin),
		NewPin:   kss.HashedPin(newPin),
809
810
811
812
813
814
815
	}

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

817
818
	switch res.Status {
	case kssPinSuccess:
819
		client.handler.ChangePinSuccess(managerID)
820
	case kssPinFailure:
821
822
823
824
825
		attempts, err := strconv.Atoi(res.Message)
		if err != nil {
			return err
		}
		client.handler.ChangePinIncorrect(managerID, attempts)
826
	case kssPinError:
827
828
829
830
831
		timeout, err := strconv.Atoi(res.Message)
		if err != nil {
			return err
		}
		client.handler.ChangePinBlocked(managerID, timeout)
832
833
	default:
		return errors.New("Unknown keyshare response")
834
	}
835

836
837
838
	return nil
}