client.go 21.6 KB
Newer Older
1
2
3
package irmago

import (
4
	"crypto/rand"
Sietse Ringers's avatar
Sietse Ringers committed
5
	"math/big"
Sietse Ringers's avatar
Sietse Ringers committed
6
	"sort"
7
	"time"
Sietse Ringers's avatar
Sietse Ringers committed
8

9
	"github.com/credentials/go-go-gadget-paillier"
Sietse Ringers's avatar
Sietse Ringers committed
10
	"github.com/go-errors/errors"
11
12
13
	"github.com/mhe/gabi"
)

14
// This file contains most methods of the Client (c.f. session.go
Sietse Ringers's avatar
Sietse Ringers committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// and updates.go).
//
// 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
// immediately need to be available anyway,
//
// - 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).

30
// Client (de)serializes credentials and keyshare server information
Sietse Ringers's avatar
Sietse Ringers committed
31
32
33
34
// 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.
35
type Client struct {
Sietse Ringers's avatar
Sietse Ringers committed
36
	// Stuff we manage on disk
37
	secretkey        *secretKey
38
39
40
	attributes       map[CredentialTypeIdentifier][]*AttributeList
	credentials      map[CredentialTypeIdentifier]map[int]*credential
	keyshareServers  map[SchemeManagerIdentifier]*keyshareServer
41
	paillierKeyCache *paillierPrivateKey
Sietse Ringers's avatar
Sietse Ringers committed
42
	logs             []*LogEntry
Sietse Ringers's avatar
Sietse Ringers committed
43
	updates          []update
44

Sietse Ringers's avatar
Sietse Ringers committed
45
46
47
48
	// Where we store/load it to/from
	storage storage

	// Other state
49
50
51
52
53
	ConfigurationStore       *ConfigurationStore
	UnenrolledSchemeManagers []SchemeManagerIdentifier
	irmaConfigurationPath    string
	androidStoragePath       string
	handler                  ClientHandler
54
55
56
}

// KeyshareHandler is used for asking the user for his email address and PIN,
57
// for enrolling at a keyshare server.
58
type KeyshareHandler interface {
59
60
	EnrollmentError(manager SchemeManagerIdentifier, err error)
	EnrollmentSuccess(manager SchemeManagerIdentifier)
61
62
63
64
65
66
67
}

type ClientHandler interface {
	KeyshareHandler

	UpdateConfigurationStore(new *IrmaIdentifierSet)
	UpdateAttributes()
Sietse Ringers's avatar
Sietse Ringers committed
68
69
}

70
71
72
73
type secretKey struct {
	Key *big.Int
}

74
// NewClient creates a new Client that uses the directory
75
76
77
78
// 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),
79
// and handler is used for informing the user of new stuff, and when a
80
// enrollment to a keyshare server needs to happen.
81
// The client returned by this function has been fully deserialized
82
83
// and is ready for use.
//
Sietse Ringers's avatar
Sietse Ringers committed
84
85
// NOTE: It is the responsibility of the caller that there exists a (properly
// protected) directory at storagePath!
86
func NewClient(
87
88
89
	storagePath string,
	irmaConfigurationPath string,
	androidStoragePath string,
90
	handler ClientHandler,
91
) (*Client, error) {
92
93
94
95
96
97
98
99
	var err error
	if err = AssertPathExists(storagePath); err != nil {
		return nil, err
	}
	if err = AssertPathExists(irmaConfigurationPath); err != nil {
		return nil, err
	}

100
	cm := &Client{
101
102
103
104
105
		credentials:           make(map[CredentialTypeIdentifier]map[int]*credential),
		keyshareServers:       make(map[SchemeManagerIdentifier]*keyshareServer),
		attributes:            make(map[CredentialTypeIdentifier][]*AttributeList),
		irmaConfigurationPath: irmaConfigurationPath,
		androidStoragePath:    androidStoragePath,
106
		handler:               handler,
107
108
109
110
111
112
113
114
	}

	cm.ConfigurationStore, err = NewConfigurationStore(storagePath+"/irma_configuration", irmaConfigurationPath)
	if err != nil {
		return nil, err
	}
	if err = cm.ConfigurationStore.ParseFolder(); err != nil {
		return nil, err
115
116
117
	}

	// Ensure storage path exists, and populate it with necessary files
118
	cm.storage = storage{storagePath: storagePath, ConfigurationStore: cm.ConfigurationStore}
Sietse Ringers's avatar
Sietse Ringers committed
119
	if err = cm.storage.EnsureStorageExists(); err != nil {
120
121
122
		return nil, err
	}

123
	// Perform new update functions from clientUpdates, if any
124
125
126
127
128
	if err = cm.update(); err != nil {
		return nil, err
	}

	// Load our stuff
Sietse Ringers's avatar
Sietse Ringers committed
129
	if cm.secretkey, err = cm.storage.LoadSecretKey(); err != nil {
130
131
		return nil, err
	}
Sietse Ringers's avatar
Sietse Ringers committed
132
	if cm.attributes, err = cm.storage.LoadAttributes(); err != nil {
133
134
		return nil, err
	}
135
	if cm.keyshareServers, err = cm.storage.LoadKeyshareServers(); err != nil {
136
137
		return nil, err
	}
138
	if cm.paillierKeyCache, err = cm.storage.LoadPaillierKeys(); err != nil {
139
140
		return nil, err
	}
141
142
143
	if cm.paillierKeyCache == nil {
		cm.paillierKey(false)
	}
144

145
146
	cm.UnenrolledSchemeManagers = cm.unenrolledSchemeManagers()
	if len(cm.UnenrolledSchemeManagers) > 1 {
147
148
149
150
151
152
		return nil, errors.New("Too many keyshare servers")
	}

	return cm, nil
}

153
// CredentialInfoList returns a list of information of all contained credentials.
154
func (client *Client) CredentialInfoList() CredentialInfoList {
155
	list := CredentialInfoList([]*CredentialInfo{})
156

157
	for _, attrlistlist := range client.attributes {
158
159
160
		for index, attrlist := range attrlistlist {
			info := attrlist.Info()
			info.Index = index
161
			list = append(list, info)
Sietse Ringers's avatar
Sietse Ringers committed
162
163
		}
	}
164

Sietse Ringers's avatar
Sietse Ringers committed
165
166
167
168
	sort.Sort(list)
	return list
}

169
// addCredential adds the specified credential to the Client, saving its signature
Sietse Ringers's avatar
Sietse Ringers committed
170
// imediately, and optionally cm.attributes as well.
171
func (client *Client) addCredential(cred *credential, storeAttributes bool) (err error) {
Sietse Ringers's avatar
Sietse Ringers committed
172
173
	id := cred.CredentialType().Identifier()

174
	// Don't add duplicate creds
175
	for _, attrlistlist := range client.attributes {
176
177
178
179
180
181
182
183
		for _, attrs := range attrlistlist {
			if attrs.hash() == cred.AttributeList().hash() {
				return nil
			}
		}
	}

	// If this is a singleton credential type, ensure we have at most one by removing any previous instance
184
185
	if cred.CredentialType().IsSingleton && len(client.creds(id)) > 0 {
		client.remove(id, 0, false) // Index is 0, because if we're here we have exactly one
186
187
188
	}

	// Append the new cred to our attributes and credentials
189
190
191
	client.attributes[id] = append(client.attrs(id), cred.AttributeList())
	if _, exists := client.credentials[id]; !exists {
		client.credentials[id] = make(map[int]*credential)
Sietse Ringers's avatar
Sietse Ringers committed
192
	}
193
194
	counter := len(client.attributes[id]) - 1
	client.credentials[id][counter] = cred
Sietse Ringers's avatar
Sietse Ringers committed
195

196
	if err = client.storage.StoreSignature(cred); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
197
198
199
		return
	}
	if storeAttributes {
200
		err = client.storage.StoreAttributes(client.attributes)
Sietse Ringers's avatar
Sietse Ringers committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
	}
	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

215
func (client *Client) remove(id CredentialTypeIdentifier, index int, storenow bool) error {
216
	// Remove attributes
217
	list, exists := client.attributes[id]
218
219
220
221
	if !exists || index >= len(list) {
		return errors.Errorf("Can't remove credential %s-%d: no such credential", id.String(), index)
	}
	attrs := list[index]
222
	client.attributes[id] = append(list[:index], list[index+1:]...)
223
	if storenow {
224
		if err := client.storage.StoreAttributes(client.attributes); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
225
226
			return err
		}
227
228
229
	}

	// Remove credential
230
	if creds, exists := client.credentials[id]; exists {
231
		if _, exists := creds[index]; exists {
Sietse Ringers's avatar
Sietse Ringers committed
232
			delete(creds, index)
233
			client.credentials[id] = creds
234
235
236
237
		}
	}

	// Remove signature from storage
238
	if err := client.storage.DeleteSignature(attrs); err != nil {
239
240
241
		return err
	}

242
243
244
245
	removed := map[CredentialTypeIdentifier][]TranslatedString{}
	removed[id] = attrs.Strings()

	if storenow {
246
		return client.addLogEntry(&LogEntry{
247
248
249
250
251
252
			Type:    actionRemoval,
			Time:    Timestamp(time.Now()),
			Removed: removed,
		})
	}
	return nil
253
254
}

255
256
func (client *Client) RemoveCredential(id CredentialTypeIdentifier, index int) error {
	return client.remove(id, index, true)
257
258
}

259
260
func (client *Client) RemoveCredentialByHash(hash string) error {
	cred, index, err := client.credentialByHash(hash)
261
262
263
	if err != nil {
		return err
	}
264
	return client.RemoveCredential(cred.CredentialType().Identifier(), index)
265
266
}

267
func (client *Client) RemoveAllCredentials() error {
268
	removed := map[CredentialTypeIdentifier][]TranslatedString{}
269
	for _, attrlistlist := range client.attributes {
Sietse Ringers's avatar
Sietse Ringers committed
270
271
272
273
		for _, attrs := range attrlistlist {
			if attrs.CredentialType() != nil {
				removed[attrs.CredentialType().Identifier()] = attrs.Strings()
			}
274
			client.storage.DeleteSignature(attrs)
275
276
		}
	}
277
278
	client.attributes = map[CredentialTypeIdentifier][]*AttributeList{}
	if err := client.storage.StoreAttributes(client.attributes); err != nil {
279
280
		return err
	}
281
282
283
284
285
286

	logentry := &LogEntry{
		Type:    actionRemoval,
		Time:    Timestamp(time.Now()),
		Removed: removed,
	}
287
	if err := client.addLogEntry(logentry); err != nil {
288
289
		return err
	}
290
	return client.storage.StoreLogs(client.logs)
291
292
}

293
// Attribute and credential getter methods
Sietse Ringers's avatar
Sietse Ringers committed
294

Sietse Ringers's avatar
Sietse Ringers committed
295
// attrs returns cm.attributes[id], initializing it to an empty slice if neccesary
296
297
func (client *Client) attrs(id CredentialTypeIdentifier) []*AttributeList {
	list, exists := client.attributes[id]
Sietse Ringers's avatar
Sietse Ringers committed
298
299
	if !exists {
		list = make([]*AttributeList, 0, 1)
300
		client.attributes[id] = list
Sietse Ringers's avatar
Sietse Ringers committed
301
302
303
304
305
	}
	return list
}

// creds returns cm.credentials[id], initializing it to an empty map if neccesary
306
307
func (client *Client) creds(id CredentialTypeIdentifier) map[int]*credential {
	list, exists := client.credentials[id]
Sietse Ringers's avatar
Sietse Ringers committed
308
	if !exists {
Sietse Ringers's avatar
Sietse Ringers committed
309
		list = make(map[int]*credential)
310
		client.credentials[id] = list
Sietse Ringers's avatar
Sietse Ringers committed
311
312
313
314
	}
	return list
}

Sietse Ringers's avatar
Sietse Ringers committed
315
// Attributes returns the attribute list of the requested credential, or nil if we do not have it.
316
317
func (client *Client) Attributes(id CredentialTypeIdentifier, counter int) (attributes *AttributeList) {
	list := client.attrs(id)
Sietse Ringers's avatar
Sietse Ringers committed
318
	if len(list) <= counter {
Sietse Ringers's avatar
Sietse Ringers committed
319
320
321
322
323
		return
	}
	return list[counter]
}

324
325
func (client *Client) credentialByHash(hash string) (*credential, int, error) {
	for _, attrlistlist := range client.attributes {
326
327
		for index, attrs := range attrlistlist {
			if attrs.hash() == hash {
328
				cred, err := client.credential(attrs.CredentialType().Identifier(), index)
329
330
331
332
333
334
335
				return cred, index, err
			}
		}
	}
	return nil, 0, nil
}

336
337
func (client *Client) credentialByID(id CredentialIdentifier) (*credential, error) {
	if _, exists := client.attributes[id.Type]; !exists {
Sietse Ringers's avatar
Sietse Ringers committed
338
339
		return nil, nil
	}
340
	for index, attrs := range client.attributes[id.Type] {
Sietse Ringers's avatar
Sietse Ringers committed
341
		if attrs.hash() == id.Hash {
342
			return client.credential(attrs.CredentialType().Identifier(), index)
Sietse Ringers's avatar
Sietse Ringers committed
343
344
345
		}
	}
	return nil, nil
346
347
}

Sietse Ringers's avatar
Sietse Ringers committed
348
// credential returns the requested credential, or nil if we do not have it.
349
func (client *Client) credential(id CredentialTypeIdentifier, counter int) (cred *credential, err error) {
Sietse Ringers's avatar
Sietse Ringers committed
350
	// If the requested credential is not in credential map, we check if its attributes were
351
	// deserialized during NewClient(). If so, there should be a corresponding signature file,
Sietse Ringers's avatar
Sietse Ringers committed
352
	// so we read that, construct the credential, and add it to the credential map
353
354
	if _, exists := client.creds(id)[counter]; !exists {
		attrs := client.Attributes(id, counter)
Sietse Ringers's avatar
Sietse Ringers committed
355
356
357
		if attrs == nil { // We do not have the requested cred
			return
		}
358
		sig, err := client.storage.LoadSignature(attrs)
Sietse Ringers's avatar
Sietse Ringers committed
359
360
361
362
363
364
365
		if err != nil {
			return nil, err
		}
		if sig == nil {
			err = errors.New("signature file not found")
			return nil, err
		}
366
		pk, err := attrs.PublicKey()
367
368
369
		if err != nil {
			return nil, err
		}
370
371
372
		if pk == nil {
			return nil, errors.New("unknown public key")
		}
373
		cred, err := newCredential(&gabi.Credential{
374
			Attributes: append([]*big.Int{client.secretkey.Key}, attrs.Ints...),
375
			Signature:  sig,
376
			Pk:         pk,
377
		}, client.ConfigurationStore)
378
379
380
		if err != nil {
			return nil, err
		}
381
		client.credentials[id][counter] = cred
Sietse Ringers's avatar
Sietse Ringers committed
382
383
	}

384
	return client.credentials[id][counter], nil
385
386
}

Sietse Ringers's avatar
Sietse Ringers committed
387
// Methods used in the IRMA protocol
388

389
// Candidates returns a list of attributes present in this client
Sietse Ringers's avatar
Sietse Ringers committed
390
// that satisfy the specified attribute disjunction.
391
func (client *Client) Candidates(disjunction *AttributeDisjunction) []*AttributeIdentifier {
392
	candidates := make([]*AttributeIdentifier, 0, 10)
393
394

	for _, attribute := range disjunction.Attributes {
Sietse Ringers's avatar
Sietse Ringers committed
395
		credID := attribute.CredentialTypeIdentifier()
396
		if !client.ConfigurationStore.Contains(credID) {
397
398
			continue
		}
399
		creds := client.attributes[credID]
400
401
402
403
		count := len(creds)
		if count == 0 {
			continue
		}
404
405
		for _, attrs := range creds {
			id := &AttributeIdentifier{Type: attribute, Hash: attrs.hash()}
406
407
408
			if attribute.IsCredential() {
				candidates = append(candidates, id)
			} else {
Sietse Ringers's avatar
Sietse Ringers committed
409
				val := attrs.untranslatedAttribute(attribute)
410
				if val == "" { // This won't handle empty attributes correctly
411
412
413
414
415
416
417
418
419
420
421
422
					continue
				}
				if !disjunction.HasValues() || val == disjunction.Values[attribute] {
					candidates = append(candidates, id)
				}
			}
		}
	}

	return candidates
}

423
// CheckSatisfiability checks if this client has the required attributes
Sietse Ringers's avatar
Sietse Ringers committed
424
425
// to satisfy the specifed disjunction list. If not, the unsatisfiable disjunctions
// are returned.
426
func (client *Client) CheckSatisfiability(
427
428
429
430
431
432
	disjunctions AttributeDisjunctionList,
) ([][]*AttributeIdentifier, AttributeDisjunctionList) {
	candidates := [][]*AttributeIdentifier{}
	missing := AttributeDisjunctionList{}
	for i, disjunction := range disjunctions {
		candidates = append(candidates, []*AttributeIdentifier{})
433
		candidates[i] = client.Candidates(disjunction)
434
		if len(candidates[i]) == 0 {
435
436
437
			missing = append(missing, disjunction)
		}
	}
438
	return candidates, missing
439
}
440

441
func (client *Client) groupCredentials(choice *DisclosureChoice) (map[CredentialIdentifier][]int, error) {
442
	grouped := make(map[CredentialIdentifier][]int)
443
444
445
	if choice == nil || choice.Attributes == nil {
		return grouped, nil
	}
446
447
448
449
450
451
452
453

	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 {
454
455
			indices := make([]int, 1, 1)
			indices[0] = 1 // Always include metadata
456
457
458
459
460
461
			grouped[ici] = indices
		}

		if identifier.IsCredential() {
			continue // In this case we only disclose the metadata attribute, which is already handled
		}
462
		index, err := client.ConfigurationStore.CredentialTypes[identifier.CredentialTypeIdentifier()].IndexOf(identifier)
463
464
465
466
		if err != nil {
			return nil, err
		}

Sietse Ringers's avatar
Sietse Ringers committed
467
		// These indices will be used in the []*big.Int at gabi.credential.Attributes,
468
		// which doesn't know about the secret key and metadata attribute, so +2
469
		grouped[ici] = append(grouped[ici], index+2)
470
471
472
473
474
	}

	return grouped, nil
}

475
// ProofBuilders constructs a list of proof builders for the specified attribute choice.
476
477
func (client *Client) ProofBuilders(choice *DisclosureChoice) (gabi.ProofBuilderList, error) {
	todisclose, err := client.groupCredentials(choice)
478
479
480
481
	if err != nil {
		return nil, err
	}

482
	builders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
483
	for id, list := range todisclose {
484
		cred, err := client.credentialByID(id)
485
486
487
488
489
		if err != nil {
			return nil, err
		}
		builders = append(builders, cred.Credential.CreateDisclosureProofBuilder(list))
	}
Sietse Ringers's avatar
Sietse Ringers committed
490
	return builders, nil
491
}
Sietse Ringers's avatar
Sietse Ringers committed
492

Sietse Ringers's avatar
Sietse Ringers committed
493
// Proofs computes disclosure proofs containing the attributes specified by choice.
494
495
func (client *Client) Proofs(choice *DisclosureChoice, request IrmaSession, issig bool) (gabi.ProofList, error) {
	builders, err := client.ProofBuilders(choice)
Sietse Ringers's avatar
Sietse Ringers committed
496
497
498
	if err != nil {
		return nil, err
	}
499
	return builders.BuildProofList(request.GetContext(), request.GetNonce(), issig), nil
Sietse Ringers's avatar
Sietse Ringers committed
500
501
}

502
503
// IssuanceProofBuilders constructs a list of proof builders in the issuance protocol
// for the future credentials as well as possibly any disclosed attributes.
504
func (client *Client) IssuanceProofBuilders(request *IssuanceRequest) (gabi.ProofBuilderList, error) {
Sietse Ringers's avatar
Cleanup    
Sietse Ringers committed
505
	state, err := newIssuanceState()
Sietse Ringers's avatar
Sietse Ringers committed
506
507
508
509
510
	if err != nil {
		return nil, err
	}
	request.state = state

511
	proofBuilders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
Sietse Ringers's avatar
Sietse Ringers committed
512
	for _, futurecred := range request.Credentials {
Sietse Ringers's avatar
Sietse Ringers committed
513
		var pk *gabi.PublicKey
514
		pk, err = client.ConfigurationStore.PublicKey(futurecred.CredentialTypeID.IssuerIdentifier(), futurecred.KeyCounter)
515
516
517
		if err != nil {
			return nil, err
		}
518
		credBuilder := gabi.NewCredentialBuilder(
519
			pk, request.GetContext(), client.secretkey.Key, state.nonce2)
Sietse Ringers's avatar
Sietse Ringers committed
520
521
522
		request.state.builders = append(request.state.builders, credBuilder)
		proofBuilders = append(proofBuilders, credBuilder)
	}
Sietse Ringers's avatar
Sietse Ringers committed
523

524
	disclosures, err := client.ProofBuilders(request.choice)
Sietse Ringers's avatar
Sietse Ringers committed
525
526
527
	if err != nil {
		return nil, err
	}
Sietse Ringers's avatar
Sietse Ringers committed
528
	proofBuilders = append(disclosures, proofBuilders...)
Sietse Ringers's avatar
Sietse Ringers committed
529
530
	return proofBuilders, nil
}
Sietse Ringers's avatar
Sietse Ringers committed
531

Sietse Ringers's avatar
Sietse Ringers committed
532
533
// IssueCommitments computes issuance commitments, along with disclosure proofs
// specified by choice.
534
535
func (client *Client) IssueCommitments(request *IssuanceRequest) (*gabi.IssueCommitmentMessage, error) {
	proofBuilders, err := client.IssuanceProofBuilders(request)
Sietse Ringers's avatar
Sietse Ringers committed
536
537
538
	if err != nil {
		return nil, err
	}
539
	list := proofBuilders.BuildProofList(request.GetContext(), request.GetNonce(), false)
Sietse Ringers's avatar
Sietse Ringers committed
540
	return &gabi.IssueCommitmentMessage{Proofs: list, Nonce2: request.state.nonce2}, nil
Sietse Ringers's avatar
Sietse Ringers committed
541
542
}

Sietse Ringers's avatar
Sietse Ringers committed
543
544
// ConstructCredentials constructs and saves new credentials
// using the specified issuance signature messages.
545
func (client *Client) ConstructCredentials(msg []*gabi.IssueSignatureMessage, request *IssuanceRequest) error {
Sietse Ringers's avatar
Sietse Ringers committed
546
547
548
549
	if len(msg) != len(request.state.builders) {
		return errors.New("Received unexpected amount of signatures")
	}

550
551
	// 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
552
	gabicreds := []*gabi.Credential{}
Sietse Ringers's avatar
Sietse Ringers committed
553
	for i, sig := range msg {
554
		attrs, err := request.Credentials[i].AttributeList(client.ConfigurationStore)
Sietse Ringers's avatar
Sietse Ringers committed
555
556
557
558
559
560
561
		if err != nil {
			return err
		}
		cred, err := request.state.builders[i].ConstructCredential(sig, attrs.Ints)
		if err != nil {
			return err
		}
562
		gabicreds = append(gabicreds, cred)
Sietse Ringers's avatar
Sietse Ringers committed
563
564
	}

565
	for _, gabicred := range gabicreds {
566
		newcred, err := newCredential(gabicred, client.ConfigurationStore)
567
568
569
		if err != nil {
			return err
		}
570
		if err = client.addCredential(newcred, true); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
571
572
			return err
		}
Sietse Ringers's avatar
Sietse Ringers committed
573
	}
574

Sietse Ringers's avatar
Sietse Ringers committed
575
	return nil
Sietse Ringers's avatar
Sietse Ringers committed
576
}
577

Sietse Ringers's avatar
Sietse Ringers committed
578
579
// Keyshare server handling

580
// PaillierKey returns a new Paillier key (and generates a new one in a goroutine).
581
582
func (client *Client) paillierKey(wait bool) *paillierPrivateKey {
	cached := client.paillierKeyCache
Sietse Ringers's avatar
Sietse Ringers committed
583
	ch := make(chan bool)
584

585
586
	// 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
587
	// the if-clause below match.
588
	go client.paillierKeyWorker(cached == nil && wait, ch)
589
	if cached == nil && wait {
Sietse Ringers's avatar
Sietse Ringers committed
590
		<-ch
591
		// generate yet another one for future calls, but no need to wait now
592
		go client.paillierKeyWorker(false, ch)
Sietse Ringers's avatar
Sietse Ringers committed
593
	}
594
	return client.paillierKeyCache
595
}
Sietse Ringers's avatar
Sietse Ringers committed
596

597
func (client *Client) paillierKeyWorker(wait bool, ch chan bool) {
598
	newkey, _ := paillier.GenerateKey(rand.Reader, 2048)
599
600
	client.paillierKeyCache = (*paillierPrivateKey)(newkey)
	client.storage.StorePaillierKeys(client.paillierKeyCache)
601
602
603
604
605
	if wait {
		ch <- true
	}
}

606
func (client *Client) unenrolledSchemeManagers() []SchemeManagerIdentifier {
Sietse Ringers's avatar
Sietse Ringers committed
607
	list := []SchemeManagerIdentifier{}
608
609
	for name, manager := range client.ConfigurationStore.SchemeManagers {
		if _, contains := client.keyshareServers[name]; manager.Distributed() && !contains {
Sietse Ringers's avatar
Sietse Ringers committed
610
			list = append(list, manager.Identifier())
Sietse Ringers's avatar
Sietse Ringers committed
611
612
613
614
		}
	}
	return list
}
Sietse Ringers's avatar
Sietse Ringers committed
615

616
// KeyshareEnroll attempts to enroll at the keyshare server of the specified scheme manager.
617
func (client *Client) KeyshareEnroll(manager SchemeManagerIdentifier, email, pin string) {
Sietse Ringers's avatar
Sietse Ringers committed
618
	go func() {
619
620
		defer func() {
			handlePanic(func(err *SessionError) {
621
622
				if client.handler != nil {
					client.handler.EnrollmentError(manager, err)
623
624
625
626
				}
			})
		}()

627
628
		err := client.keyshareEnrollWorker(manager, email, pin)
		client.UnenrolledSchemeManagers = client.unenrolledSchemeManagers()
Sietse Ringers's avatar
Sietse Ringers committed
629
		if err != nil {
630
			client.handler.EnrollmentError(manager, err)
Sietse Ringers's avatar
Sietse Ringers committed
631
		} else {
632
			client.handler.EnrollmentSuccess(manager)
Sietse Ringers's avatar
Sietse Ringers committed
633
634
		}
	}()
635

636
637
}

638
639
func (client *Client) keyshareEnrollWorker(managerID SchemeManagerIdentifier, email, pin string) error {
	manager, ok := client.ConfigurationStore.SchemeManagers[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
640
641
642
643
644
645
646
647
648
649
650
	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")
	}

	transport := NewHTTPTransport(manager.KeyshareServer)
651
	kss, err := newKeyshareServer(client.paillierKey(true), manager.KeyshareServer, email)
Sietse Ringers's avatar
Sietse Ringers committed
652
653
654
	if err != nil {
		return err
	}
655
	message := keyshareEnrollment{
Sietse Ringers's avatar
Sietse Ringers committed
656
657
658
659
660
661
662
663
664
665
666
		Username:  email,
		Pin:       kss.HashedPin(pin),
		PublicKey: (*paillierPublicKey)(&kss.PrivateKey.PublicKey),
	}

	result := &struct{}{}
	err = transport.Post("web/users/selfenroll", result, message)
	if err != nil {
		return err
	}

667
668
	client.keyshareServers[managerID] = kss
	return client.storage.StoreKeyshareServers(client.keyshareServers)
Sietse Ringers's avatar
Sietse Ringers committed
669
670
}

671
// KeyshareRemove unenrolls the keyshare server of the specified scheme manager.
672
673
func (client *Client) KeyshareRemove(manager SchemeManagerIdentifier) error {
	if _, contains := client.keyshareServers[manager]; !contains {
Sietse Ringers's avatar
Sietse Ringers committed
674
675
		return errors.New("Can't uninstall unknown keyshare server")
	}
676
677
	delete(client.keyshareServers, manager)
	return client.storage.StoreKeyshareServers(client.keyshareServers)
Sietse Ringers's avatar
Sietse Ringers committed
678
}
Sietse Ringers's avatar
Sietse Ringers committed
679

680
681
682
683
func (client *Client) KeyshareRemoveAll() error {
	client.keyshareServers = map[SchemeManagerIdentifier]*keyshareServer{}
	client.UnenrolledSchemeManagers = client.unenrolledSchemeManagers()
	return client.storage.StoreKeyshareServers(client.keyshareServers)
684
685
}

Sietse Ringers's avatar
Sietse Ringers committed
686
687
// Add, load and store log entries

688
689
690
func (client *Client) addLogEntry(entry *LogEntry) error {
	client.logs = append(client.logs, entry)
	return client.storage.StoreLogs(client.logs)
691
	return nil
Sietse Ringers's avatar
Sietse Ringers committed
692
693
}

694
695
func (client *Client) Logs() ([]*LogEntry, error) {
	if client.logs == nil || len(client.logs) == 0 {
Sietse Ringers's avatar
Sietse Ringers committed
696
		var err error
697
		client.logs, err = client.storage.LoadLogs()
Sietse Ringers's avatar
Sietse Ringers committed
698
699
700
701
		if err != nil {
			return nil, err
		}
	}
702
	return client.logs, nil
Sietse Ringers's avatar
Sietse Ringers committed
703
}