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

import (
4
	"crypto/rand"
Sietse Ringers's avatar
Sietse Ringers committed
5
	"math/big"
Sietse Ringers's avatar
Sietse Ringers committed
6
	"sort"
7
	"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
61
	Preferences           Preferences
	Configuration         *irma.Configuration
	irmaConfigurationPath string
	androidStoragePath    string
	handler               ClientHandler
	state                 *issuanceState
62
63
}

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

68
69
type Preferences struct {
	EnableCrashReporting bool
70
71
}

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

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

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

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

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

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

104
// New creates a new Client that uses the directory
105
106
107
108
// specified by storagePath for (de)serializing itself. irmaConfigurationPath
// is the path to a (possibly readonly) folder containing irma_configuration;
// androidStoragePath is an optional path to the files of the old android app
// (specify "" if you do not want to parse the old android app files),
109
// and handler is used for informing the user of new stuff, and when a
110
// enrollment to a keyshare server needs to happen.
111
// The client returned by this function has been fully deserialized
112
113
// and is ready for use.
//
Sietse Ringers's avatar
Sietse Ringers committed
114
115
// NOTE: It is the responsibility of the caller that there exists a (properly
// protected) directory at storagePath!
116
func New(
117
118
119
	storagePath string,
	irmaConfigurationPath string,
	androidStoragePath string,
120
	handler ClientHandler,
121
) (*Client, error) {
122
	var err error
123
	if err = fs.AssertPathExists(storagePath); err != nil {
124
125
		return nil, err
	}
126
	if err = fs.AssertPathExists(irmaConfigurationPath); err != nil {
127
128
129
		return nil, err
	}

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

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

144
	schemeMgrErr := cm.Configuration.ParseOrRestoreFolder()
145
146
147
148
149
	// If schemMgrErr is of type SchemeManagerError, we continue and
	// return it at the end; otherwise bail out now
	_, isSchemeMgrErr := schemeMgrErr.(*irma.SchemeManagerError)
	if schemeMgrErr != nil && !isSchemeMgrErr {
		return nil, schemeMgrErr
150
	}
151
152

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

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

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

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

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

189
	return cm, schemeMgrErr
190
191
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return candidates
}

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

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

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

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

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

	return grouped, nil
}

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

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

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

568
569
570
571
	return builders, nil
}

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

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

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

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

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

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

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

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

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

Sietse Ringers's avatar
Sietse Ringers committed
654
	return nil
Sietse Ringers's avatar
Sietse Ringers committed
655
}
656

Sietse Ringers's avatar
Sietse Ringers committed
657
658
// Keyshare server handling

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

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

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

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

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

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

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

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

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

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

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

	return nil
Sietse Ringers's avatar
Sietse Ringers committed
756
757
}

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

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

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

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

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

805
806
807
	return nil
}

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

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

Sietse Ringers's avatar
Sietse Ringers committed
823
824
// Add, load and store log entries

825
826
827
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
828
829
}

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