client.go 26.8 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
	"github.com/mhe/gabi"
13
	"github.com/mhe/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
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.SessionRequest, 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
	return builders, nil
}

// Proofs computes disclosure proofs containing the attributes specified by choice.
570
func (client *Client) Proofs(choice *irma.DisclosureChoice, request irma.SessionRequest, issig bool) (gabi.ProofList, error) {
571
572
573
574
575
	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
581
582
583
// 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)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

813
814
815
	return nil
}

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

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

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

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

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