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

import (
4
	"crypto/rand"
Sietse Ringers's avatar
Sietse Ringers committed
5
	"math/big"
Sietse Ringers's avatar
Sietse Ringers committed
6
	"sort"
7
	"strconv"
8
	"time"
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
	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
197
		for index, attrlist := range attrlistlist {
			info := attrlist.Info()
198
199
200
			if info == nil {
				continue
			}
201
			info.Index = index
202
			list = append(list, info)
Sietse Ringers's avatar
Sietse Ringers committed
203
204
		}
	}
205

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

435
	return client.credentialsCache[id][counter], nil
436
437
}

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

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

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

	return candidates
}

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

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

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

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

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

	return grouped, nil
}

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

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

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

567
568
569
570
	return builders, nil
}

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

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

580
581
582
583
584
// 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)
}

585
// IssuanceProofBuilders constructs a list of proof builders in the issuance protocol
586
587
588
589
// 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.
func (client *Client) IssuanceProofBuilders(request *irma.IssuanceRequest) (gabi.ProofBuilderList, *big.Int, error) {
	issuerProofNonce, err := generateIssuerProofNonce()
Sietse Ringers's avatar
Sietse Ringers committed
590
	if err != nil {
591
		return nil, nil, err
Sietse Ringers's avatar
Sietse Ringers committed
592
	}
593
	builders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
Sietse Ringers's avatar
Sietse Ringers committed
594
	for _, futurecred := range request.Credentials {
Sietse Ringers's avatar
Sietse Ringers committed
595
		var pk *gabi.PublicKey
596
		pk, err = client.Configuration.PublicKey(futurecred.CredentialTypeID.IssuerIdentifier(), futurecred.KeyCounter)
597
		if err != nil {
598
			return nil, nil, err
599
		}
600
		credBuilder := gabi.NewCredentialBuilder(
601
602
			pk, request.GetContext(), client.secretkey.Key, issuerProofNonce)
		builders = append(builders, credBuilder)
Sietse Ringers's avatar
Sietse Ringers committed
603
	}
Sietse Ringers's avatar
Sietse Ringers committed
604

605
	disclosures, err := client.ProofBuilders(request.Choice, request, false)
Sietse Ringers's avatar
Sietse Ringers committed
606
	if err != nil {
607
		return nil, nil, err
Sietse Ringers's avatar
Sietse Ringers committed
608
	}
609
610
	builders = append(disclosures, builders...)
	return builders, issuerProofNonce, nil
Sietse Ringers's avatar
Sietse Ringers committed
611
}
Sietse Ringers's avatar
Sietse Ringers committed
612

613
614
615
616
// 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.
func (client *Client) IssueCommitments(request *irma.IssuanceRequest) (*gabi.IssueCommitmentMessage, gabi.ProofBuilderList, error) {
	builders, issuerProofNonce, err := client.IssuanceProofBuilders(request)
Sietse Ringers's avatar
Sietse Ringers committed
617
	if err != nil {
618
		return nil, nil, err
Sietse Ringers's avatar
Sietse Ringers committed
619
	}
620
621
	list := builders.BuildProofList(request.GetContext(), request.GetNonce(), false)
	return &gabi.IssueCommitmentMessage{Proofs: list, Nonce2: issuerProofNonce}, builders, nil
Sietse Ringers's avatar
Sietse Ringers committed
622
623
}

624
625
626
627
// 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
628
629
630
		return errors.New("Received unexpected amount of signatures")
	}

631
632
	// 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
633
	gabicreds := []*gabi.Credential{}
634
635
636
637
638
639
640
641
642
	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
643
644
645
		if err != nil {
			return err
		}
646
		cred, err := credbuilder.ConstructCredential(sig, attrs.Ints)
Sietse Ringers's avatar
Sietse Ringers committed
647
648
649
		if err != nil {
			return err
		}
650
		gabicreds = append(gabicreds, cred)
Sietse Ringers's avatar
Sietse Ringers committed
651
652
	}

653
	for _, gabicred := range gabicreds {
654
		newcred, err := newCredential(gabicred, client.Configuration)
655
656
657
		if err != nil {
			return err
		}
658
		if err = client.addCredential(newcred, true); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
659
660
			return err
		}
Sietse Ringers's avatar
Sietse Ringers committed
661
	}
662

Sietse Ringers's avatar
Sietse Ringers committed
663
	return nil
Sietse Ringers's avatar
Sietse Ringers committed
664
}
665

Sietse Ringers's avatar
Sietse Ringers committed
666
667
// Keyshare server handling

668
// PaillierKey returns a new Paillier key (and generates a new one in a goroutine).
669
670
func (client *Client) paillierKey(wait bool) *paillierPrivateKey {
	cached := client.paillierKeyCache
Sietse Ringers's avatar
Sietse Ringers committed
671
	ch := make(chan bool)
672

673
674
	// 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
675
	// the if-clause below match.
676
	go client.paillierKeyWorker(cached == nil && wait, ch)
677
	if cached == nil && wait {
Sietse Ringers's avatar
Sietse Ringers committed
678
		<-ch
679
		// generate yet another one for future calls, but no need to wait now
680
		go client.paillierKeyWorker(false, ch)
Sietse Ringers's avatar
Sietse Ringers committed
681
	}
682
	return client.paillierKeyCache
683
}
Sietse Ringers's avatar
Sietse Ringers committed
684

685
func (client *Client) paillierKeyWorker(wait bool, ch chan bool) {
686
	newkey, _ := paillier.GenerateKey(rand.Reader, 2048)
687
688
	client.paillierKeyCache = (*paillierPrivateKey)(newkey)
	client.storage.StorePaillierKeys(client.paillierKeyCache)
689
690
691
692
693
	if wait {
		ch <- true
	}
}

694
func (client *Client) genSchemeManagersList(enrolled bool) []irma.SchemeManagerIdentifier {
695
	list := []irma.SchemeManagerIdentifier{}
696
	for name, manager := range client.Configuration.SchemeManagers {
697
		if _, contains := client.keyshareServers[name]; manager.Distributed() && contains == enrolled {
Sietse Ringers's avatar
Sietse Ringers committed
698
			list = append(list, manager.Identifier())
Sietse Ringers's avatar
Sietse Ringers committed
699
700
701
702
		}
	}
	return list
}
Sietse Ringers's avatar
Sietse Ringers committed
703

704
705
706
707
func (client *Client) UnenrolledSchemeManagers() []irma.SchemeManagerIdentifier {
	return client.genSchemeManagersList(false)
}

708
func (client *Client) EnrolledSchemeManagers() []irma.SchemeManagerIdentifier {
709
	return client.genSchemeManagersList(true)
710
711
}

712
// KeyshareEnroll attempts to enroll at the keyshare server of the specified scheme manager.
713
func (client *Client) KeyshareEnroll(manager irma.SchemeManagerIdentifier, email *string, pin string, lang string) {
Sietse Ringers's avatar
Sietse Ringers committed
714
	go func() {
715
		err := client.keyshareEnrollWorker(manager, email, pin, lang)
Sietse Ringers's avatar
Sietse Ringers committed
716
		if err != nil {
Tomas's avatar
Tomas committed
717
			client.handler.EnrollmentFailure(manager, err)
Sietse Ringers's avatar
Sietse Ringers committed
718
719
		}
	}()
720
721
}

722
func (client *Client) keyshareEnrollWorker(managerID irma.SchemeManagerIdentifier, email *string, pin string, lang string) error {
723
	manager, ok := client.Configuration.SchemeManagers[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
724
725
726
727
728
729
730
731
732
733
	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")
	}

734
	transport := irma.NewHTTPTransport(manager.KeyshareServer)
735
	kss, err := newKeyshareServer(managerID, client.paillierKey(true), manager.KeyshareServer)
Sietse Ringers's avatar
Sietse Ringers committed
736
737
738
	if err != nil {
		return err
	}
739
	message := keyshareEnrollment{
740
		Email:     email,
Sietse Ringers's avatar
Sietse Ringers committed
741
		Pin:       kss.HashedPin(pin),
742
		Language:  lang,
Sietse Ringers's avatar
Sietse Ringers committed
743
744
745
		PublicKey: (*paillierPublicKey)(&kss.PrivateKey.PublicKey),
	}

746
747
	qr := &irma.Qr{}
	err = transport.Post("client/register", qr, message)
Sietse Ringers's avatar
Sietse Ringers committed
748
749
750
751
	if err != nil {
		return err
	}

752
753
754
755
756
	// 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.
757
	client.keyshareServers[managerID] = kss
758
	client.newQrSession(qr, &keyshareEnrollmentHandler{
759
760
761
762
763
764
		client: client,
		pin:    pin,
		kss:    kss,
	})

	return nil
Sietse Ringers's avatar
Sietse Ringers committed
765
766
}

767
func (client *Client) KeyshareChangePin(manager irma.SchemeManagerIdentifier, oldPin string, newPin string) {
768
	go func() {
769
		err := client.keyshareChangePinWorker(manager, oldPin, newPin)
770
		if err != nil {
771
			client.handler.ChangePinFailure(manager, err)
772
773
774
775
		}
	}()
}

776
func (client *Client) keyshareChangePinWorker(managerID irma.SchemeManagerIdentifier, oldPin string, newPin string) error {
777
778
779
780
781
782
	kss, ok := client.keyshareServers[managerID]
	if !ok {
		return errors.New("Unknown keyshare server")
	}

	transport := irma.NewHTTPTransport(kss.URL)
783
	message := keyshareChangepin{
784
		Username: kss.Username,
785
786
		OldPin:   kss.HashedPin(oldPin),
		NewPin:   kss.HashedPin(newPin),
787
788
789
790
791
792
793
	}

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

795
796
	switch res.Status {
	case kssPinSuccess:
797
		client.handler.ChangePinSuccess(managerID)
798
	case kssPinFailure:
799
800
801
802
803
		attempts, err := strconv.Atoi(res.Message)
		if err != nil {
			return err
		}
		client.handler.ChangePinIncorrect(managerID, attempts)
804
	case kssPinError:
805
806
807
808
809
		timeout, err := strconv.Atoi(res.Message)
		if err != nil {
			return err
		}
		client.handler.ChangePinBlocked(managerID, timeout)
810
811
	default:
		return errors.New("Unknown keyshare response")
812
	}
813

814
815
816
	return nil
}

817
// KeyshareRemove unenrolls the keyshare server of the specified scheme manager.
818
func (client *Client) KeyshareRemove(manager irma.SchemeManagerIdentifier) error {
819
	if _, contains := client.keyshareServers[manager]; !contains {
Sietse Ringers's avatar
Sietse Ringers committed
820
821
		return errors.New("Can't uninstall unknown keyshare server")
	}
822
823
	delete(client.keyshareServers, manager)
	return client.storage.StoreKeyshareServers(client.keyshareServers)
Sietse Ringers's avatar
Sietse Ringers committed
824
}
Sietse Ringers's avatar
Sietse Ringers committed
825

Sietse Ringers's avatar
Sietse Ringers committed
826
// KeyshareRemoveAll removes all keyshare server registrations.
827
func (client *Client) KeyshareRemoveAll() error {
828
	client.keyshareServers = map[irma.SchemeManagerIdentifier]*keyshareServer{}
829
	return client.storage.StoreKeyshareServers(client.keyshareServers)
830
831
}

Sietse Ringers's avatar
Sietse Ringers committed
832
833
// Add, load and store log entries

834
835
836
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
837
838
}

Sietse Ringers's avatar
Sietse Ringers committed
839
// Logs returns the log entries of past events.
840
841
func (client *Client) Logs() ([]*LogEntry, error) {
	if client.logs == nil || len(client.logs) == 0 {
Sietse Ringers's avatar
Sietse Ringers committed
842
		var err error
843
		client.logs, err = client.storage.LoadLogs()
Sietse Ringers's avatar
Sietse Ringers committed
844
845
846
847
		if err != nil {
			return nil, err
		}
	}
848
	return client.logs, nil