manager.go 13.2 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
7
	"sort"

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

// CredentialManager manages credentials.
type CredentialManager struct {
15
	secretkey        *secretKey
16
17
18
19
	storagePath      string
	attributes       map[CredentialTypeIdentifier][]*AttributeList
	credentials      map[CredentialTypeIdentifier]map[int]*credential
	keyshareServers  map[SchemeManagerIdentifier]*keyshareServer
20
	paillierKeyCache *paillierPrivateKey
Sietse Ringers's avatar
Sietse Ringers committed
21
	logs             []*LogEntry
22

23
	irmaConfigurationPath string
24
	androidStoragePath    string
25
	ConfigurationStore    *ConfigurationStore
26
	updates               []update
Sietse Ringers's avatar
Sietse Ringers committed
27
28
}

29
30
31
32
type secretKey struct {
	Key *big.Int
}

33
34
35
// CredentialInfoList returns a list of information of all contained credentials.
func (cm *CredentialManager) CredentialInfoList() CredentialInfoList {
	list := CredentialInfoList([]*CredentialInfo{})
36
37

	for _, attrlistlist := range cm.attributes {
38
39
40
		for index, attrlist := range attrlistlist {
			info := attrlist.Info()
			info.Index = index
41
			list = append(list, attrlist.Info())
Sietse Ringers's avatar
Sietse Ringers committed
42
43
		}
	}
44

Sietse Ringers's avatar
Sietse Ringers committed
45
46
47
48
	sort.Sort(list)
	return list
}

49
50
51
52
53
54
func (cm *CredentialManager) generateSecretKey() (*secretKey, error) {
	key, err := gabi.RandomBigInt(gabi.DefaultSystemParameters[1024].Lm)
	if err != nil {
		return nil, err
	}
	return &secretKey{Key: key}, nil
55
56
}

Sietse Ringers's avatar
Sietse Ringers committed
57
// attrs returns cm.attributes[id], initializing it to an empty slice if neccesary
58
func (cm *CredentialManager) attrs(id CredentialTypeIdentifier) []*AttributeList {
Sietse Ringers's avatar
Sietse Ringers committed
59
60
61
62
63
64
65
66
67
	list, exists := cm.attributes[id]
	if !exists {
		list = make([]*AttributeList, 0, 1)
		cm.attributes[id] = list
	}
	return list
}

// creds returns cm.credentials[id], initializing it to an empty map if neccesary
Sietse Ringers's avatar
Sietse Ringers committed
68
func (cm *CredentialManager) creds(id CredentialTypeIdentifier) map[int]*credential {
Sietse Ringers's avatar
Sietse Ringers committed
69
70
	list, exists := cm.credentials[id]
	if !exists {
Sietse Ringers's avatar
Sietse Ringers committed
71
		list = make(map[int]*credential)
Sietse Ringers's avatar
Sietse Ringers committed
72
73
74
75
76
		cm.credentials[id] = list
	}
	return list
}

Sietse Ringers's avatar
Sietse Ringers committed
77
// Attributes returns the attribute list of the requested credential, or nil if we do not have it.
78
func (cm *CredentialManager) Attributes(id CredentialTypeIdentifier, counter int) (attributes *AttributeList) {
Sietse Ringers's avatar
Sietse Ringers committed
79
80
	list := cm.attrs(id)
	if len(list) <= counter {
Sietse Ringers's avatar
Sietse Ringers committed
81
82
83
84
85
		return
	}
	return list[counter]
}

Sietse Ringers's avatar
Sietse Ringers committed
86
87
func (cm *CredentialManager) credentialByID(id CredentialIdentifier) (cred *credential, err error) {
	return cm.credential(id.Type, id.Index)
88
89
}

Sietse Ringers's avatar
Sietse Ringers committed
90
91
// credential returns the requested credential, or nil if we do not have it.
func (cm *CredentialManager) credential(id CredentialTypeIdentifier, counter int) (cred *credential, err error) {
Sietse Ringers's avatar
Sietse Ringers committed
92
	// If the requested credential is not in credential map, we check if its attributes were
93
	// deserialized during NewCredentialManager(). If so, there should be a corresponding signature file,
Sietse Ringers's avatar
Sietse Ringers committed
94
	// so we read that, construct the credential, and add it to the credential map
Sietse Ringers's avatar
Sietse Ringers committed
95
	if _, exists := cm.creds(id)[counter]; !exists {
Sietse Ringers's avatar
Sietse Ringers committed
96
97
98
99
		attrs := cm.Attributes(id, counter)
		if attrs == nil { // We do not have the requested cred
			return
		}
100
		sig, err := cm.loadSignature(attrs)
Sietse Ringers's avatar
Sietse Ringers committed
101
102
103
104
105
106
107
		if err != nil {
			return nil, err
		}
		if sig == nil {
			err = errors.New("signature file not found")
			return nil, err
		}
108
		pk, err := attrs.PublicKey()
109
110
111
		if err != nil {
			return nil, err
		}
112
113
114
		if pk == nil {
			return nil, errors.New("unknown public key")
		}
115
		cred, err := newCredential(&gabi.Credential{
116
			Attributes: append([]*big.Int{cm.secretkey.Key}, attrs.Ints...),
117
			Signature:  sig,
118
			Pk:         pk,
119
		}, cm.ConfigurationStore)
120
121
122
		if err != nil {
			return nil, err
		}
Sietse Ringers's avatar
Sietse Ringers committed
123
124
125
126
		cm.credentials[id][counter] = cred
	}

	return cm.credentials[id][counter], nil
127
128
}

129
130
131
// addCredential adds the specified credential to the CredentialManager, saving its signature
// imediately, and optionally cm.attributes as well.
func (cm *CredentialManager) addCredential(cred *credential, storeAttributes bool) (err error) {
132
	id := cred.CredentialType().Identifier()
133
	cm.attributes[id] = append(cm.attrs(id), cred.AttributeList())
134

135
	if _, exists := cm.credentials[id]; !exists {
Sietse Ringers's avatar
Sietse Ringers committed
136
		cm.credentials[id] = make(map[int]*credential)
137
	}
Sietse Ringers's avatar
Sietse Ringers committed
138
139
	counter := len(cm.attributes[id]) - 1
	cm.credentials[id][counter] = cred
140

141
	if err = cm.storeSignature(cred, counter); err != nil {
142
143
		return
	}
144
145
146
	if storeAttributes {
		err = cm.storeAttributes()
	}
147
148
	return
}
149

Sietse Ringers's avatar
Sietse Ringers committed
150
151
// Candidates returns a list of attributes present in this credential manager
// that satisfy the specified attribute disjunction.
152
func (cm *CredentialManager) Candidates(disjunction *AttributeDisjunction) []*AttributeIdentifier {
153
	candidates := make([]*AttributeIdentifier, 0, 10)
154
155

	for _, attribute := range disjunction.Attributes {
Sietse Ringers's avatar
Sietse Ringers committed
156
		credID := attribute.CredentialTypeIdentifier()
157
		if !cm.ConfigurationStore.Contains(credID) {
158
159
			continue
		}
Sietse Ringers's avatar
Sietse Ringers committed
160
		creds := cm.credentials[credID]
161
162
163
164
165
166
167
168
169
		count := len(creds)
		if count == 0 {
			continue
		}
		for i, cred := range creds {
			id := &AttributeIdentifier{Type: attribute, Index: i, Count: count}
			if attribute.IsCredential() {
				candidates = append(candidates, id)
			} else {
170
				attrs := cred.AttributeList()
Sietse Ringers's avatar
Sietse Ringers committed
171
				val := attrs.untranslatedAttribute(attribute)
172
				if val == "" { // This won't handle empty attributes correctly
173
174
175
176
177
178
179
180
181
182
183
184
					continue
				}
				if !disjunction.HasValues() || val == disjunction.Values[attribute] {
					candidates = append(candidates, id)
				}
			}
		}
	}

	return candidates
}

Sietse Ringers's avatar
Sietse Ringers committed
185
186
187
// CheckSatisfiability checks if this credential manager has the required attributes
// to satisfy the specifed disjunction list. If not, the unsatisfiable disjunctions
// are returned.
Sietse Ringers's avatar
Sietse Ringers committed
188
func (cm *CredentialManager) CheckSatisfiability(disjunctions AttributeDisjunctionList) AttributeDisjunctionList {
189
	missing := make(AttributeDisjunctionList, 0, 5)
Sietse Ringers's avatar
Sietse Ringers committed
190
	for _, disjunction := range disjunctions {
191
192
193
194
195
196
197
		if len(cm.Candidates(disjunction)) == 0 {
			missing = append(missing, disjunction)
		}
	}

	return missing
}
198

199
func (cm *CredentialManager) groupCredentials(choice *DisclosureChoice) (map[CredentialIdentifier][]int, error) {
200
201
202
203
204
205
206
207
208
	grouped := make(map[CredentialIdentifier][]int)

	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 {
209
210
			indices := make([]int, 1, 1)
			indices[0] = 1 // Always include metadata
211
212
213
214
215
216
			grouped[ici] = indices
		}

		if identifier.IsCredential() {
			continue // In this case we only disclose the metadata attribute, which is already handled
		}
217
		index, err := cm.ConfigurationStore.Credentials[identifier.CredentialTypeIdentifier()].IndexOf(identifier)
218
219
220
221
		if err != nil {
			return nil, err
		}

Sietse Ringers's avatar
Sietse Ringers committed
222
		// These indices will be used in the []*big.Int at gabi.credential.Attributes,
223
		// which doesn't know about the secret key and metadata attribute, so +2
224
		grouped[ici] = append(grouped[ici], index+2)
225
226
227
228
229
	}

	return grouped, nil
}

230
231
// IrmaSession is an IRMA session.
type IrmaSession interface {
232
	GetNonce() *big.Int
Sietse Ringers's avatar
Sietse Ringers committed
233
	SetNonce(*big.Int)
234
	GetContext() *big.Int
Sietse Ringers's avatar
Sietse Ringers committed
235
236
	SetContext(*big.Int)
	DisjunctionList() AttributeDisjunctionList
Sietse Ringers's avatar
Sietse Ringers committed
237
238
	DisclosureChoice() *DisclosureChoice
	SetDisclosureChoice(choice *DisclosureChoice)
239
	Distributed(store *ConfigurationStore) bool
Sietse Ringers's avatar
Sietse Ringers committed
240
	SchemeManagers() []SchemeManagerIdentifier
241
242
}

243
// ProofBuilders constructs a list of proof builders for the specified attribute choice.
244
func (cm *CredentialManager) ProofBuilders(choice *DisclosureChoice) (gabi.ProofBuilderList, error) {
245
246
247
248
249
	todisclose, err := cm.groupCredentials(choice)
	if err != nil {
		return nil, err
	}

250
	builders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
251
	for id, list := range todisclose {
Sietse Ringers's avatar
Sietse Ringers committed
252
		cred, err := cm.credentialByID(id)
253
254
255
256
257
		if err != nil {
			return nil, err
		}
		builders = append(builders, cred.Credential.CreateDisclosureProofBuilder(list))
	}
Sietse Ringers's avatar
Sietse Ringers committed
258
	return builders, nil
259
}
Sietse Ringers's avatar
Sietse Ringers committed
260

Sietse Ringers's avatar
Sietse Ringers committed
261
// Proofs computes disclosure proofs containing the attributes specified by choice.
262
func (cm *CredentialManager) Proofs(choice *DisclosureChoice, request IrmaSession, issig bool) (gabi.ProofList, error) {
Sietse Ringers's avatar
Sietse Ringers committed
263
	builders, err := cm.ProofBuilders(choice)
Sietse Ringers's avatar
Sietse Ringers committed
264
265
266
	if err != nil {
		return nil, err
	}
267
	return builders.BuildProofList(request.GetContext(), request.GetNonce(), issig), nil
Sietse Ringers's avatar
Sietse Ringers committed
268
269
}

270
271
// IssuanceProofBuilders constructs a list of proof builders in the issuance protocol
// for the future credentials as well as possibly any disclosed attributes.
272
func (cm *CredentialManager) IssuanceProofBuilders(request *IssuanceRequest) (gabi.ProofBuilderList, error) {
Sietse Ringers's avatar
Cleanup    
Sietse Ringers committed
273
	state, err := newIssuanceState()
Sietse Ringers's avatar
Sietse Ringers committed
274
275
276
277
278
	if err != nil {
		return nil, err
	}
	request.state = state

279
	proofBuilders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
Sietse Ringers's avatar
Sietse Ringers committed
280
	for _, futurecred := range request.Credentials {
281
		pk, err := cm.ConfigurationStore.PublicKey(futurecred.Credential.IssuerIdentifier(), futurecred.KeyCounter)
282
283
284
		if err != nil {
			return nil, err
		}
285
286
		credBuilder := gabi.NewCredentialBuilder(
			pk, request.GetContext(), cm.secretkey.Key, state.nonce2)
Sietse Ringers's avatar
Sietse Ringers committed
287
288
289
		request.state.builders = append(request.state.builders, credBuilder)
		proofBuilders = append(proofBuilders, credBuilder)
	}
Sietse Ringers's avatar
Sietse Ringers committed
290

Sietse Ringers's avatar
Sietse Ringers committed
291
	disclosures, err := cm.ProofBuilders(request.choice)
Sietse Ringers's avatar
Sietse Ringers committed
292
293
294
	if err != nil {
		return nil, err
	}
Sietse Ringers's avatar
Sietse Ringers committed
295
	proofBuilders = append(disclosures, proofBuilders...)
Sietse Ringers's avatar
Sietse Ringers committed
296
297
	return proofBuilders, nil
}
Sietse Ringers's avatar
Sietse Ringers committed
298

Sietse Ringers's avatar
Sietse Ringers committed
299
300
301
302
303
304
305
// IssueCommitments computes issuance commitments, along with disclosure proofs
// specified by choice.
func (cm *CredentialManager) IssueCommitments(request *IssuanceRequest) (*gabi.IssueCommitmentMessage, error) {
	proofBuilders, err := cm.IssuanceProofBuilders(request)
	if err != nil {
		return nil, err
	}
306
	list := proofBuilders.BuildProofList(request.GetContext(), request.GetNonce(), false)
Sietse Ringers's avatar
Sietse Ringers committed
307
	return &gabi.IssueCommitmentMessage{Proofs: list, Nonce2: request.state.nonce2}, nil
Sietse Ringers's avatar
Sietse Ringers committed
308
309
}

Sietse Ringers's avatar
Sietse Ringers committed
310
311
// ConstructCredentials constructs and saves new credentials
// using the specified issuance signature messages.
Sietse Ringers's avatar
Sietse Ringers committed
312
313
314
315
316
func (cm *CredentialManager) ConstructCredentials(msg []*gabi.IssueSignatureMessage, request *IssuanceRequest) error {
	if len(msg) != len(request.state.builders) {
		return errors.New("Received unexpected amount of signatures")
	}

317
318
	// 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
319
	gabicreds := []*gabi.Credential{}
Sietse Ringers's avatar
Sietse Ringers committed
320
	for i, sig := range msg {
321
		attrs, err := request.Credentials[i].AttributeList(cm.ConfigurationStore)
Sietse Ringers's avatar
Sietse Ringers committed
322
323
324
325
326
327
328
		if err != nil {
			return err
		}
		cred, err := request.state.builders[i].ConstructCredential(sig, attrs.Ints)
		if err != nil {
			return err
		}
329
		gabicreds = append(gabicreds, cred)
Sietse Ringers's avatar
Sietse Ringers committed
330
331
	}

332
	for _, gabicred := range gabicreds {
333
		newcred, err := newCredential(gabicred, cm.ConfigurationStore)
334
335
336
337
		if err != nil {
			return err
		}
		cm.addCredential(newcred, true)
Sietse Ringers's avatar
Sietse Ringers committed
338
	}
339

Sietse Ringers's avatar
Sietse Ringers committed
340
	return nil
Sietse Ringers's avatar
Sietse Ringers committed
341
}
342
343

// PaillierKey returns a new Paillier key (and generates a new one in a goroutine).
Sietse Ringers's avatar
Sietse Ringers committed
344
func (cm *CredentialManager) paillierKey(wait bool) *paillierPrivateKey {
345
	retval := cm.paillierKeyCache
Sietse Ringers's avatar
Sietse Ringers committed
346
	ch := make(chan bool)
347
348
349
350
	go func() {
		newkey, _ := paillier.GenerateKey(rand.Reader, 2048)
		converted := paillierPrivateKey(*newkey)
		cm.paillierKeyCache = &converted
Sietse Ringers's avatar
Sietse Ringers committed
351
352
353
		if wait && retval == nil {
			ch <- true
		}
354
	}()
Sietse Ringers's avatar
Sietse Ringers committed
355
356
357
358
	if wait && retval == nil {
		<-ch
		return cm.paillierKeyCache
	}
359
360
	return retval
}
Sietse Ringers's avatar
Sietse Ringers committed
361
362
363

func (cm *CredentialManager) unenrolledKeyshareServers() []*SchemeManager {
	list := []*SchemeManager{}
364
	for name, manager := range cm.ConfigurationStore.SchemeManagers {
Sietse Ringers's avatar
Sietse Ringers committed
365
366
367
368
369
370
		if _, contains := cm.keyshareServers[name]; len(manager.KeyshareServer) > 0 && !contains {
			list = append(list, manager)
		}
	}
	return list
}
Sietse Ringers's avatar
Sietse Ringers committed
371

372
373
// KeyshareEnroll attempts to register at the keyshare server of the specified scheme manager.
func (cm *CredentialManager) KeyshareEnroll(managerID SchemeManagerIdentifier, email, pin string) error {
374
	manager, ok := cm.ConfigurationStore.SchemeManagers[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
375
376
377
378
379
380
381
382
383
384
385
	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)
386
	kss, err := newKeyshareServer(cm.paillierKey(true), manager.KeyshareServer, email)
Sietse Ringers's avatar
Sietse Ringers committed
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
	if err != nil {
		return err
	}
	message := keyshareRegistration{
		Username:  email,
		Pin:       kss.HashedPin(pin),
		PublicKey: (*paillierPublicKey)(&kss.PrivateKey.PublicKey),
	}

	// TODO: examine error returned by Post() to see if it tells us that the email address is already in use
	result := &struct{}{}
	err = transport.Post("web/users/selfenroll", result, message)
	if err != nil {
		return err
	}

403
	cm.keyshareServers[managerID] = kss
Sietse Ringers's avatar
Sietse Ringers committed
404
405
406
	return cm.storeKeyshareServers()
}

407
// KeyshareRemove unregisters the keyshare server of the specified scheme manager.
Sietse Ringers's avatar
Sietse Ringers committed
408
409
410
411
412
func (cm *CredentialManager) KeyshareRemove(manager SchemeManagerIdentifier) error {
	if _, contains := cm.keyshareServers[manager]; !contains {
		return errors.New("Can't uninstall unknown keyshare server")
	}
	delete(cm.keyshareServers, manager)
Sietse Ringers's avatar
Sietse Ringers committed
413
414
	return cm.storeKeyshareServers()
}
Sietse Ringers's avatar
Sietse Ringers committed
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430

func (cm *CredentialManager) addLogEntry(entry *LogEntry) error {
	cm.logs = append(cm.logs, entry)
	return cm.storeLogs()
}

func (cm *CredentialManager) Logs() ([]*LogEntry, error) {
	if cm.logs == nil || len(cm.logs) == 0 {
		var err error
		cm.logs, err = cm.loadLogs()
		if err != nil {
			return nil, err
		}
	}
	return cm.logs, nil
}