manager.go 12.5 KB
Newer Older
1
2
3
4
5
6
package irmago

import (
	"errors"
	"math/big"

7
8
	"crypto/rand"

Sietse Ringers's avatar
Sietse Ringers committed
9
10
	"sort"

11
	"github.com/credentials/go-go-gadget-paillier"
12
13
14
15
16
	"github.com/mhe/gabi"
)

// CredentialManager manages credentials.
type CredentialManager struct {
17
18
19
20
21
	secretkey        *big.Int
	storagePath      string
	attributes       map[CredentialTypeIdentifier][]*AttributeList
	credentials      map[CredentialTypeIdentifier]map[int]*credential
	keyshareServers  map[SchemeManagerIdentifier]*keyshareServer
22
	paillierKeyCache *paillierPrivateKey
23

24
	Store *ConfigurationStore
Sietse Ringers's avatar
Sietse Ringers committed
25
26
}

27
28
29
// CredentialInfoList returns a list of information of all contained credentials.
func (cm *CredentialManager) CredentialInfoList() CredentialInfoList {
	list := CredentialInfoList([]*CredentialInfo{})
30
31
32

	for _, attrlistlist := range cm.attributes {
		for _, attrlist := range attrlistlist {
33
			list = append(list, attrlist.Info())
Sietse Ringers's avatar
Sietse Ringers committed
34
35
		}
	}
36

Sietse Ringers's avatar
Sietse Ringers committed
37
38
39
40
	sort.Sort(list)
	return list
}

Sietse Ringers's avatar
Sietse Ringers committed
41
42
func (cm *CredentialManager) generateSecretKey() (sk *big.Int, err error) {
	return gabi.RandomBigInt(gabi.DefaultSystemParameters[1024].Lm)
43
44
}

Sietse Ringers's avatar
Sietse Ringers committed
45
// attrs returns cm.attributes[id], initializing it to an empty slice if neccesary
46
func (cm *CredentialManager) attrs(id CredentialTypeIdentifier) []*AttributeList {
Sietse Ringers's avatar
Sietse Ringers committed
47
48
49
50
51
52
53
54
55
	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
56
func (cm *CredentialManager) creds(id CredentialTypeIdentifier) map[int]*credential {
Sietse Ringers's avatar
Sietse Ringers committed
57
58
	list, exists := cm.credentials[id]
	if !exists {
Sietse Ringers's avatar
Sietse Ringers committed
59
		list = make(map[int]*credential)
Sietse Ringers's avatar
Sietse Ringers committed
60
61
62
63
64
		cm.credentials[id] = list
	}
	return list
}

Sietse Ringers's avatar
Sietse Ringers committed
65
// Attributes returns the attribute list of the requested credential, or nil if we do not have it.
66
func (cm *CredentialManager) Attributes(id CredentialTypeIdentifier, counter int) (attributes *AttributeList) {
Sietse Ringers's avatar
Sietse Ringers committed
67
68
	list := cm.attrs(id)
	if len(list) <= counter {
Sietse Ringers's avatar
Sietse Ringers committed
69
70
71
72
73
		return
	}
	return list[counter]
}

Sietse Ringers's avatar
Sietse Ringers committed
74
75
func (cm *CredentialManager) credentialByID(id CredentialIdentifier) (cred *credential, err error) {
	return cm.credential(id.Type, id.Index)
76
77
}

Sietse Ringers's avatar
Sietse Ringers committed
78
79
// 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
80
	// If the requested credential is not in credential map, we check if its attributes were
81
	// deserialized during NewCredentialManager(). If so, there should be a corresponding signature file,
Sietse Ringers's avatar
Sietse Ringers committed
82
	// so we read that, construct the credential, and add it to the credential map
Sietse Ringers's avatar
Sietse Ringers committed
83
	if _, exists := cm.creds(id)[counter]; !exists {
Sietse Ringers's avatar
Sietse Ringers committed
84
85
86
87
88
89
90
91
92
93
94
95
96
		attrs := cm.Attributes(id, counter)
		if attrs == nil { // We do not have the requested cred
			return
		}
		ints := append([]*big.Int{cm.secretkey}, attrs.Ints...)
		sig, err := cm.loadSignature(id, counter)
		if err != nil {
			return nil, err
		}
		if sig == nil {
			err = errors.New("signature file not found")
			return nil, err
		}
97
		meta := MetadataFromInt(ints[1], cm.Store)
98
99
100
101
		pk, err := meta.PublicKey()
		if err != nil {
			return nil, err
		}
102
103
104
		if pk == nil {
			return nil, errors.New("unknown public key")
		}
105
		cred, err := newCredential(&gabi.Credential{
106
107
			Attributes: ints,
			Signature:  sig,
108
			Pk:         pk,
109
		}, cm.Store)
110
111
112
		if err != nil {
			return nil, err
		}
Sietse Ringers's avatar
Sietse Ringers committed
113
114
115
116
		cm.credentials[id][counter] = cred
	}

	return cm.credentials[id][counter], nil
117
118
}

119
120
121
// 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) {
122
	attrs := NewAttributeListFromInts(cred.Attributes[1:], cm.Store)
123
	id := cred.CredentialType().Identifier()
124
	cm.attributes[id] = append(cm.attrs(id), attrs)
125

126
	if _, exists := cm.credentials[id]; !exists {
Sietse Ringers's avatar
Sietse Ringers committed
127
		cm.credentials[id] = make(map[int]*credential)
128
	}
Sietse Ringers's avatar
Sietse Ringers committed
129
130
	counter := len(cm.attributes[id]) - 1
	cm.credentials[id][counter] = cred
131

132
	if err = cm.storeSignature(cred, counter); err != nil {
133
134
		return
	}
135
136
137
	if storeAttributes {
		err = cm.storeAttributes()
	}
138
139
	return
}
140

Sietse Ringers's avatar
Sietse Ringers committed
141
142
// Candidates returns a list of attributes present in this credential manager
// that satisfy the specified attribute disjunction.
143
func (cm *CredentialManager) Candidates(disjunction *AttributeDisjunction) []*AttributeIdentifier {
144
	candidates := make([]*AttributeIdentifier, 0, 10)
145
146

	for _, attribute := range disjunction.Attributes {
Sietse Ringers's avatar
Sietse Ringers committed
147
		credID := attribute.CredentialTypeIdentifier()
148
		if !cm.Store.Contains(credID) {
149
150
			continue
		}
Sietse Ringers's avatar
Sietse Ringers committed
151
		creds := cm.credentials[credID]
152
153
154
155
156
157
158
159
160
		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 {
161
				attrs := NewAttributeListFromInts(cred.Attributes[1:], cm.Store)
162
				val := attrs.Attribute(attribute)
163
				if val == "" { // This won't handle empty attributes correctly
164
165
166
167
168
169
170
171
172
173
174
175
					continue
				}
				if !disjunction.HasValues() || val == disjunction.Values[attribute] {
					candidates = append(candidates, id)
				}
			}
		}
	}

	return candidates
}

Sietse Ringers's avatar
Sietse Ringers committed
176
177
178
// 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
179
func (cm *CredentialManager) CheckSatisfiability(disjunctions AttributeDisjunctionList) AttributeDisjunctionList {
180
	missing := make(AttributeDisjunctionList, 0, 5)
Sietse Ringers's avatar
Sietse Ringers committed
181
	for _, disjunction := range disjunctions {
182
183
184
185
186
187
188
		if len(cm.Candidates(disjunction)) == 0 {
			missing = append(missing, disjunction)
		}
	}

	return missing
}
189

190
func (cm *CredentialManager) groupCredentials(choice *DisclosureChoice) (map[CredentialIdentifier][]int, error) {
191
192
193
194
195
196
197
198
199
	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 {
200
201
			indices := make([]int, 1, 1)
			indices[0] = 1 // Always include metadata
202
203
204
205
206
207
			grouped[ici] = indices
		}

		if identifier.IsCredential() {
			continue // In this case we only disclose the metadata attribute, which is already handled
		}
208
		index, err := cm.Store.Credentials[identifier.CredentialTypeIdentifier()].IndexOf(identifier)
209
210
211
212
		if err != nil {
			return nil, err
		}

Sietse Ringers's avatar
Sietse Ringers committed
213
		// These indices will be used in the []*big.Int at gabi.credential.Attributes,
214
		// which doesn't know about the secret key and metadata attribute, so +2
215
		grouped[ici] = append(grouped[ici], index+2)
216
217
218
219
220
	}

	return grouped, nil
}

221
222
// IrmaSession is an IRMA session.
type IrmaSession interface {
223
	GetNonce() *big.Int
Sietse Ringers's avatar
Sietse Ringers committed
224
	SetNonce(*big.Int)
225
	GetContext() *big.Int
Sietse Ringers's avatar
Sietse Ringers committed
226
227
	SetContext(*big.Int)
	DisjunctionList() AttributeDisjunctionList
Sietse Ringers's avatar
Sietse Ringers committed
228
229
	DisclosureChoice() *DisclosureChoice
	SetDisclosureChoice(choice *DisclosureChoice)
230
	Distributed(store *ConfigurationStore) bool
Sietse Ringers's avatar
Sietse Ringers committed
231
	SchemeManagers() []SchemeManagerIdentifier
232
233
}

234
// ProofBuilders constructs a list of proof builders for the specified attribute choice.
235
func (cm *CredentialManager) ProofBuilders(choice *DisclosureChoice) (gabi.ProofBuilderList, error) {
236
237
238
239
240
	todisclose, err := cm.groupCredentials(choice)
	if err != nil {
		return nil, err
	}

241
	builders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
242
	for id, list := range todisclose {
Sietse Ringers's avatar
Sietse Ringers committed
243
		cred, err := cm.credentialByID(id)
244
245
246
247
248
		if err != nil {
			return nil, err
		}
		builders = append(builders, cred.Credential.CreateDisclosureProofBuilder(list))
	}
Sietse Ringers's avatar
Sietse Ringers committed
249
	return builders, nil
250
}
Sietse Ringers's avatar
Sietse Ringers committed
251

Sietse Ringers's avatar
Sietse Ringers committed
252
// Proofs computes disclosure proofs containing the attributes specified by choice.
253
func (cm *CredentialManager) Proofs(choice *DisclosureChoice, request IrmaSession, issig bool) (gabi.ProofList, error) {
Sietse Ringers's avatar
Sietse Ringers committed
254
	builders, err := cm.ProofBuilders(choice)
Sietse Ringers's avatar
Sietse Ringers committed
255
256
257
	if err != nil {
		return nil, err
	}
258
	return builders.BuildProofList(request.GetContext(), request.GetNonce(), issig), nil
Sietse Ringers's avatar
Sietse Ringers committed
259
260
}

261
262
// IssuanceProofBuilders constructs a list of proof builders in the issuance protocol
// for the future credentials as well as possibly any disclosed attributes.
263
func (cm *CredentialManager) IssuanceProofBuilders(request *IssuanceRequest) (gabi.ProofBuilderList, error) {
Sietse Ringers's avatar
Cleanup    
Sietse Ringers committed
264
	state, err := newIssuanceState()
Sietse Ringers's avatar
Sietse Ringers committed
265
266
267
268
269
	if err != nil {
		return nil, err
	}
	request.state = state

270
	proofBuilders := gabi.ProofBuilderList([]gabi.ProofBuilder{})
Sietse Ringers's avatar
Sietse Ringers committed
271
	for _, futurecred := range request.Credentials {
272
273
274
275
		pk, err := cm.Store.PublicKey(futurecred.Credential.IssuerIdentifier(), futurecred.KeyCounter)
		if err != nil {
			return nil, err
		}
Sietse Ringers's avatar
Sietse Ringers committed
276
277
278
279
		credBuilder := gabi.NewCredentialBuilder(pk, request.GetContext(), cm.secretkey, state.nonce2)
		request.state.builders = append(request.state.builders, credBuilder)
		proofBuilders = append(proofBuilders, credBuilder)
	}
Sietse Ringers's avatar
Sietse Ringers committed
280

Sietse Ringers's avatar
Sietse Ringers committed
281
	disclosures, err := cm.ProofBuilders(request.choice)
Sietse Ringers's avatar
Sietse Ringers committed
282
283
284
	if err != nil {
		return nil, err
	}
Sietse Ringers's avatar
Sietse Ringers committed
285
	proofBuilders = append(disclosures, proofBuilders...)
Sietse Ringers's avatar
Sietse Ringers committed
286
287
	return proofBuilders, nil
}
Sietse Ringers's avatar
Sietse Ringers committed
288

Sietse Ringers's avatar
Sietse Ringers committed
289
290
291
292
293
294
295
// 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
	}
296
	list := proofBuilders.BuildProofList(request.GetContext(), request.GetNonce(), false)
Sietse Ringers's avatar
Sietse Ringers committed
297
	return &gabi.IssueCommitmentMessage{Proofs: list, Nonce2: request.state.nonce2}, nil
Sietse Ringers's avatar
Sietse Ringers committed
298
299
}

Sietse Ringers's avatar
Sietse Ringers committed
300
301
// ConstructCredentials constructs and saves new credentials
// using the specified issuance signature messages.
Sietse Ringers's avatar
Sietse Ringers committed
302
303
304
305
306
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")
	}

307
308
	// 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
309
	gabicreds := []*gabi.Credential{}
Sietse Ringers's avatar
Sietse Ringers committed
310
	for i, sig := range msg {
311
		attrs, err := request.Credentials[i].AttributeList(cm.Store)
Sietse Ringers's avatar
Sietse Ringers committed
312
313
314
315
316
317
318
		if err != nil {
			return err
		}
		cred, err := request.state.builders[i].ConstructCredential(sig, attrs.Ints)
		if err != nil {
			return err
		}
319
		gabicreds = append(gabicreds, cred)
Sietse Ringers's avatar
Sietse Ringers committed
320
321
	}

322
323
324
325
326
327
	for _, gabicred := range gabicreds {
		newcred, err := newCredential(gabicred, cm.Store)
		if err != nil {
			return err
		}
		cm.addCredential(newcred, true)
Sietse Ringers's avatar
Sietse Ringers committed
328
	}
329

Sietse Ringers's avatar
Sietse Ringers committed
330
	return nil
Sietse Ringers's avatar
Sietse Ringers committed
331
}
332
333

// PaillierKey returns a new Paillier key (and generates a new one in a goroutine).
Sietse Ringers's avatar
Sietse Ringers committed
334
func (cm *CredentialManager) paillierKey(wait bool) *paillierPrivateKey {
335
	retval := cm.paillierKeyCache
Sietse Ringers's avatar
Sietse Ringers committed
336
	ch := make(chan bool)
337
338
339
340
	go func() {
		newkey, _ := paillier.GenerateKey(rand.Reader, 2048)
		converted := paillierPrivateKey(*newkey)
		cm.paillierKeyCache = &converted
Sietse Ringers's avatar
Sietse Ringers committed
341
342
343
		if wait && retval == nil {
			ch <- true
		}
344
	}()
Sietse Ringers's avatar
Sietse Ringers committed
345
346
347
348
	if wait && retval == nil {
		<-ch
		return cm.paillierKeyCache
	}
349
350
	return retval
}
Sietse Ringers's avatar
Sietse Ringers committed
351
352
353

func (cm *CredentialManager) unenrolledKeyshareServers() []*SchemeManager {
	list := []*SchemeManager{}
354
	for name, manager := range cm.Store.SchemeManagers {
Sietse Ringers's avatar
Sietse Ringers committed
355
356
357
358
359
360
		if _, contains := cm.keyshareServers[name]; len(manager.KeyshareServer) > 0 && !contains {
			list = append(list, manager)
		}
	}
	return list
}
Sietse Ringers's avatar
Sietse Ringers committed
361

362
363
// KeyshareEnroll attempts to register at the keyshare server of the specified scheme manager.
func (cm *CredentialManager) KeyshareEnroll(managerID SchemeManagerIdentifier, email, pin string) error {
364
	manager, ok := cm.Store.SchemeManagers[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
365
366
367
368
369
370
371
372
373
374
375
	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)
376
	kss, err := newKeyshareServer(cm.paillierKey(true), manager.KeyshareServer, email)
Sietse Ringers's avatar
Sietse Ringers committed
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
	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
	}

393
	cm.keyshareServers[managerID] = kss
Sietse Ringers's avatar
Sietse Ringers committed
394
395
396
	return cm.storeKeyshareServers()
}

397
// KeyshareRemove unregisters the keyshare server of the specified scheme manager.
Sietse Ringers's avatar
Sietse Ringers committed
398
399
400
401
402
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
403
404
	return cm.storeKeyshareServers()
}