keyshare.go 13.2 KB
Newer Older
1
2
3
4
5
6
package irmago

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
Sietse Ringers's avatar
Sietse Ringers committed
7
8
9
10
11
12
13
	"encoding/json"
	"errors"
	"strconv"

	"math/big"

	"github.com/mhe/gabi"
14
15
)

16
// KeysharePinRequestor is used to asking the user for his PIN.
Sietse Ringers's avatar
Sietse Ringers committed
17
18
19
20
21
type KeysharePinRequestor interface {
	AskPin(remainingAttempts int, callback func(proceed bool, pin string))
}

type keyshareSessionHandler interface {
Sietse Ringers's avatar
Sietse Ringers committed
22
	KeyshareDone(message interface{})
Sietse Ringers's avatar
Sietse Ringers committed
23
	KeyshareCancelled()
Sietse Ringers's avatar
Sietse Ringers committed
24
25
26
27
28
29
	KeyshareBlocked(duration int)
	KeyshareError(err error)
}

type keyshareSession struct {
	session        Session
30
	builders       gabi.ProofBuilderList
Sietse Ringers's avatar
Sietse Ringers committed
31
	transports     map[SchemeManagerIdentifier]*HTTPTransport
Sietse Ringers's avatar
Sietse Ringers committed
32
33
	sessionHandler keyshareSessionHandler
	pinRequestor   KeysharePinRequestor
Sietse Ringers's avatar
Sietse Ringers committed
34
35
36
	keyshareServer *keyshareServer
}

37
type keyshareServer struct {
Sietse Ringers's avatar
Sietse Ringers committed
38
39
40
41
	URL        string              `json:"url"`
	Username   string              `json:"username"`
	Nonce      []byte              `json:"nonce"`
	PrivateKey *paillierPrivateKey `json:"keyPair"`
Sietse Ringers's avatar
Sietse Ringers committed
42
	token      string
43
44
}

Sietse Ringers's avatar
Sietse Ringers committed
45
46
47
type keyshareRegistration struct {
	Username  string             `json:"username"`
	Pin       string             `json:"pin"`
Sietse Ringers's avatar
Sietse Ringers committed
48
49
50
	PublicKey *paillierPublicKey `json:"publicKey"`
}

Sietse Ringers's avatar
Sietse Ringers committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
type keyshareAuthorization struct {
	Status     string   `json:"status"`
	Candidates []string `json:"candidates"`
}

type keysharePinMessage struct {
	Username string `json:"id"`
	Pin      string `json:"pin"`
}

type keysharePinStatus struct {
	Status  string `json:"status"`
	Message string `json:"message"`
}

type publicKeyIdentifier struct {
	Issuer  string `json:"issuer"`
	Counter uint   `json:"counter"`
}

// TODO update protocol so this can go away
func (pki *publicKeyIdentifier) MarshalJSON() ([]byte, error) {
	temp := struct {
		Issuer  map[string]string `json:"issuer"`
		Counter uint              `json:"counter"`
	}{
		Issuer:  map[string]string{"identifier": pki.Issuer},
		Counter: pki.Counter,
	}
	return json.Marshal(temp)
}

type proofPCommitmentMap struct {
	Commitments map[publicKeyIdentifier]*gabi.ProofPCommitment `json:"c"`
}

87
88
// KeyshareHandler is used for asking the user for his email address and PIN,
// for registering at a keyshare server.
Sietse Ringers's avatar
Sietse Ringers committed
89
type KeyshareHandler interface {
Sietse Ringers's avatar
Sietse Ringers committed
90
	StartKeyshareRegistration(manager *SchemeManager, registrationCallback func(email, pin string))
91
92
}

Sietse Ringers's avatar
Sietse Ringers committed
93
94
95
96
97
98
99
100
101
102
const (
	kssUsernameHeader = "IRMA_Username"
	kssAuthHeader     = "IRMA_Authorization"
	kssAuthorized     = "authorized"
	kssTokenExpired   = "expired"
	kssPinSuccess     = "success"
	kssPinFailure     = "failure"
	kssPinError       = "error"
)

Sietse Ringers's avatar
Sietse Ringers committed
103
func newKeyshareServer(privatekey *paillierPrivateKey, url, email string) (ks *keyshareServer, err error) {
Sietse Ringers's avatar
Sietse Ringers committed
104
105
106
107
108
109
	ks = &keyshareServer{
		Nonce:      make([]byte, 32),
		URL:        url,
		Username:   email,
		PrivateKey: privatekey,
	}
110
111
112
113
114
115
116
117
	_, err = rand.Read(ks.Nonce)
	return
}

func (ks *keyshareServer) HashedPin(pin string) string {
	hash := sha256.Sum256(append(ks.Nonce, []byte(pin)...))
	return base64.RawStdEncoding.EncodeToString(hash[:])
}
Sietse Ringers's avatar
Sietse Ringers committed
118

Sietse Ringers's avatar
Sietse Ringers committed
119
120
121
122
123
124
// startKeyshareSession starts and completes the entire keyshare protocol with all involved keyshare servers
// for the specified session, merging the keyshare proofs into the specified ProofBuilder's.
// The user's pin is retrieved using the KeysharePinRequestor, repeatedly, until either it is correct; or the
// user cancels; or one of the keyshare servers blocks us.
// Error, blocked or success of the keyshare session is reported back to the keyshareSessionHandler.
func startKeyshareSession(
Sietse Ringers's avatar
Sietse Ringers committed
125
	session Session,
126
	builders gabi.ProofBuilderList,
Sietse Ringers's avatar
Sietse Ringers committed
127
128
	sessionHandler keyshareSessionHandler,
	pin KeysharePinRequestor,
Sietse Ringers's avatar
Sietse Ringers committed
129
130
) {
	ksscount := 0
131
132
	for _, managerID := range session.SchemeManagers() {
		if MetaStore.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
133
			ksscount++
134
135
			if _, registered := Manager.keyshareServers[managerID]; !registered {
				err := errors.New("Not registered to keyshare server of scheme manager " + managerID.String())
Sietse Ringers's avatar
Sietse Ringers committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
				sessionHandler.KeyshareError(err)
				return
			}
		}
	}
	if _, issuing := session.(*IssuanceRequest); issuing && ksscount > 1 {
		err := errors.New("Issuance session involving more than one keyshare servers are not supported")
		sessionHandler.KeyshareError(err)
		return
	}

	ks := &keyshareSession{
		session:        session,
		builders:       builders,
		sessionHandler: sessionHandler,
		transports:     map[SchemeManagerIdentifier]*HTTPTransport{},
Sietse Ringers's avatar
Sietse Ringers committed
152
		pinRequestor:   pin,
Sietse Ringers's avatar
Sietse Ringers committed
153
154
155
156
	}

	askPin := false

157
158
	for _, managerID := range session.SchemeManagers() {
		if !MetaStore.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
159
160
161
			continue
		}

162
		ks.keyshareServer = Manager.keyshareServers[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
163
164
165
		transport := NewHTTPTransport(ks.keyshareServer.URL)
		transport.SetHeader(kssUsernameHeader, ks.keyshareServer.Username)
		transport.SetHeader(kssAuthHeader, ks.keyshareServer.token)
166
		ks.transports[managerID] = transport
Sietse Ringers's avatar
Sietse Ringers committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

		authstatus := &keyshareAuthorization{}
		err := transport.Post("users/isAuthorized", authstatus, "")
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
			return
		}
		switch authstatus.Status {
		case kssAuthorized: // nop
		case kssTokenExpired:
			askPin = true
		default:
			ks.sessionHandler.KeyshareError(errors.New("Keyshare server returned unrecognized authirization status"))
			return
		}
	}

	if askPin {
		ks.VerifyPin(-1)
	}
}

// Ask for a pin, repeatedly if necessary, and either continue the keyshare protocol
// with authorization, or stop the keyshare protocol and inform of failure.
func (ks *keyshareSession) VerifyPin(attempts int) {
Sietse Ringers's avatar
Sietse Ringers committed
192
	ks.pinRequestor.AskPin(attempts, func(proceed bool, pin string) {
Sietse Ringers's avatar
Sietse Ringers committed
193
194
195
196
197
		success, attemptsRemaining, blocked, err := ks.verifyPinAttempt(pin)
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
			return
		}
Sietse Ringers's avatar
Sietse Ringers committed
198
199
200
		if !proceed {
			ks.sessionHandler.KeyshareCancelled()
		}
Sietse Ringers's avatar
Sietse Ringers committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
		if blocked != 0 {
			ks.sessionHandler.KeyshareBlocked(blocked)
			return
		}
		if success {
			ks.GetCommitments()
			return
		}
		// Not successful but no error and not yet blocked: try again
		ks.VerifyPin(attemptsRemaining)
	})
}

// Verify the specified pin at each of the keyshare servers involved in the specified session.
// - If the pin did not verify at one of the keyshare servers but there are attempts remaining,
// the amount of remaining attempts is returned as the second return value.
// - If the pin did not verify at one of the keyshare servers and there are no attempts remaining,
// the amount of time for which we are blocked at the keyshare server is returned as the third
// parameter.
// - If this or anything else (specified in err) goes wrong, success will be false.
// If all is ok, success will be true.
func (ks *keyshareSession) verifyPinAttempt(pin string) (success bool, tries int, blocked int, err error) {
223
224
	for _, managerID := range ks.session.SchemeManagers() {
		if !MetaStore.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
225
226
227
			continue
		}

228
229
		kss := Manager.keyshareServers[managerID]
		transport := ks.transports[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
		pinmsg := keysharePinMessage{Username: kss.Username, Pin: kss.HashedPin(pin)}
		pinresult := &keysharePinStatus{}
		err = transport.Post("users/verify/pin", pinresult, pinmsg)
		if err != nil {
			return
		}

		switch pinresult.Status {
		case kssPinSuccess:
			kss.token = pinresult.Message
			transport.SetHeader(kssAuthHeader, kss.token)
		case kssPinFailure:
			tries, err = strconv.Atoi(pinresult.Message)
			if err != nil {
				return
			}
			return
		case kssPinError:
			blocked, err = strconv.Atoi(pinresult.Message)
			if err != nil {
				return
			}
			return
		default:
			err = errors.New("Keyshare server returned unrecognized PIN status")
			return
		}
	}

	success = true
	return
}

// GetCommitments gets the commitments (first message in Schnorr zero-knowledge protocol)
// of all keyshare servers of their part of the private key, and merges these commitments
// in our own proof builders.
func (ks *keyshareSession) GetCommitments() {
	pkids := map[SchemeManagerIdentifier][]*publicKeyIdentifier{}
	commitments := map[publicKeyIdentifier]*gabi.ProofPCommitment{}

	// For each scheme manager, build a list of public keys under this manager
	// that we will use in the keyshare protocol with the keyshare server of this manager
	for _, builder := range ks.builders {
		pk := builder.PublicKey()
274
275
		managerID := NewIssuerIdentifier(pk.Issuer).SchemeManagerIdentifier()
		if !MetaStore.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
276
277
			continue
		}
278
279
		if _, contains := pkids[managerID]; !contains {
			pkids[managerID] = []*publicKeyIdentifier{}
Sietse Ringers's avatar
Sietse Ringers committed
280
		}
281
		pkids[managerID] = append(pkids[managerID], &publicKeyIdentifier{Issuer: pk.Issuer, Counter: pk.Counter})
Sietse Ringers's avatar
Sietse Ringers committed
282
283
284
285
	}

	// Now inform each keyshare server of with respect to which public keys
	// we want them to send us commitments
286
287
	for _, managerID := range ks.session.SchemeManagers() {
		if !MetaStore.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
288
289
290
			continue
		}

291
		transport := ks.transports[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
292
		comms := &proofPCommitmentMap{}
293
		err := transport.Post("prove/getCommitments", comms, pkids[managerID])
Sietse Ringers's avatar
Sietse Ringers committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
			return
		}
		for pki, c := range comms.Commitments {
			commitments[pki] = c
		}
	}

	// Merge in the commitments
	for _, builder := range ks.builders {
		pk := builder.PublicKey()
		pki := publicKeyIdentifier{Issuer: pk.Issuer, Counter: pk.Counter}
		comm, distributed := commitments[pki]
		if !distributed {
			continue
		}
		builder.MergeProofPCommitment(comm)
	}

	ks.GetProofPs()
}

// GetProofPs uses the combined commitments of all keyshare servers and ourself
// to calculate the challenge, which is sent to the keyshare servers in order to
// receive their responses (2nd and 3rd message in Schnorr zero-knowledge protocol).
func (ks *keyshareSession) GetProofPs() {
	_, issig := ks.session.(*SignatureRequest)
	_, issuing := ks.session.(*IssuanceRequest)
323
	challenge := ks.builders.Challenge(ks.session.GetContext(), ks.session.GetNonce(), issig)
Sietse Ringers's avatar
Sietse Ringers committed
324
325
326
327
328
329
330
331
332
333
334
335
336
	kssChallenge := challenge

	// In disclosure or signature sessions the challenge is Paillier encrypted.
	if !issuing {
		bytes, err := ks.keyshareServer.PrivateKey.Encrypt(challenge.Bytes())
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
		}
		kssChallenge = new(big.Int).SetBytes(bytes)
	}

	// Post the challenge, obtaining JWT's containing the ProofP's
	responses := map[SchemeManagerIdentifier]string{}
337
338
	for _, managerID := range ks.session.SchemeManagers() {
		transport, distributed := ks.transports[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
339
340
341
342
343
344
345
346
347
		if !distributed {
			continue
		}
		var jwt string
		err := transport.Post("prove/getResponse", &jwt, kssChallenge)
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
			return
		}
348
		responses[managerID] = jwt
Sietse Ringers's avatar
Sietse Ringers committed
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
	}

	ks.Finish(challenge, responses)
}

// Finish the keyshare protocol: in case of issuance, put the keyshare jwt in the
// IssueCommitmentMessage; in case of disclosure and signing, parse each keyshare jwt,
// merge in the received ProofP's, and finish.
func (ks *keyshareSession) Finish(challenge *big.Int, responses map[SchemeManagerIdentifier]string) {
	switch ks.session.(type) {
	case *DisclosureRequest:
	case *SignatureRequest:
		proofPs := make([]*gabi.ProofP, len(ks.builders))
		for i, builder := range ks.builders {
			// Parse each received JWT
364
365
			managerID := NewIssuerIdentifier(builder.PublicKey().Issuer).SchemeManagerIdentifier()
			if !MetaStore.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
366
367
368
369
370
				continue
			}
			msg := struct {
				ProofP *gabi.ProofP
			}{}
371
			_, err := jwtDecode(responses[managerID], msg)
Sietse Ringers's avatar
Sietse Ringers committed
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
			if err != nil {
				ks.sessionHandler.KeyshareError(err)
				return
			}

			// Decrypt the responses and populate a slice of ProofP's
			proofPs[i] = msg.ProofP
			bytes, err := ks.keyshareServer.PrivateKey.Decrypt(proofPs[i].C.Bytes())
			if err != nil {
				ks.sessionHandler.KeyshareError(err)
				return
			}
			proofPs[i].C = new(big.Int).SetBytes(bytes)
		}

		// Create merged proofs and finish protocol
388
		list, err := ks.builders.BuildDistributedProofList(challenge, proofPs)
Sietse Ringers's avatar
Sietse Ringers committed
389
390
391
392
393
394
395
396
397
398
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
			return
		}
		ks.sessionHandler.KeyshareDone(list)

	case *IssuanceRequest:
		// Calculate IssueCommitmentMessage, without merging in any of the received ProofP's:
		// instead, include the keyshare server's JWT in the IssueCommitmentMessage for the
		// issuance server to verify
399
		list, err := ks.builders.BuildDistributedProofList(challenge, nil)
Sietse Ringers's avatar
Sietse Ringers committed
400
401
402
403
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
			return
		}
Sietse Ringers's avatar
Sietse Ringers committed
404
		message := gabi.IssueCommitmentMessage{Proofs: list, Nonce2: ks.session.(*IssuanceRequest).state.nonce2}
Sietse Ringers's avatar
Sietse Ringers committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
		for _, response := range responses {
			message.ProofPjwt = response
			break
		}
		ks.sessionHandler.KeyshareDone(message)
	}
}

// TODO this message is ugly, should update protocol
func (comms *proofPCommitmentMap) UnmarshalJSON(bytes []byte) error {
	comms.Commitments = map[publicKeyIdentifier]*gabi.ProofPCommitment{}
	temp := struct {
		C [][]*json.RawMessage `json:"c"`
	}{}
	if err := json.Unmarshal(bytes, &temp); err != nil {
		return err
	}
	for _, raw := range temp.C {
423
		tempPkID := struct {
Sietse Ringers's avatar
Sietse Ringers committed
424
425
426
427
428
429
			Issuer struct {
				Identifier string `json:"identifier"`
			} `json:"issuer"`
			Counter uint `json:"counter"`
		}{}
		comm := gabi.ProofPCommitment{}
430
		if err := json.Unmarshal([]byte(*raw[0]), &tempPkID); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
431
432
433
434
435
			return err
		}
		if err := json.Unmarshal([]byte(*raw[1]), &comm); err != nil {
			return err
		}
436
		pkid := publicKeyIdentifier{Issuer: tempPkID.Issuer.Identifier, Counter: tempPkID.Counter}
Sietse Ringers's avatar
Sietse Ringers committed
437
438
439
440
		comms.Commitments[pkid] = &comm
	}
	return nil
}