keyshare.go 15.6 KB
Newer Older
1
package irmaclient
2
3
4
5
6

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
Sietse Ringers's avatar
Sietse Ringers committed
7
	"math/big"
Sietse Ringers's avatar
Sietse Ringers committed
8
9
	"strconv"

Sietse Ringers's avatar
Sietse Ringers committed
10
	"github.com/go-errors/errors"
Sietse Ringers's avatar
Sietse Ringers committed
11
	"github.com/mhe/gabi"
12
	"github.com/privacybydesign/irmago"
13
14
)

15
16
// This file contains an implementation of the client side of the keyshare protocol,
// as well as the keyshareSessionHandler which is used to communicate with the user
17
// (currently only Client).
18

19
// KeysharePinRequestor is used to asking the user for his PIN.
Sietse Ringers's avatar
Sietse Ringers committed
20
type KeysharePinRequestor interface {
21
	RequestPin(remainingAttempts int, callback PinHandler)
Sietse Ringers's avatar
Sietse Ringers committed
22
23
24
}

type keyshareSessionHandler interface {
Sietse Ringers's avatar
Sietse Ringers committed
25
	KeyshareDone(message interface{})
Sietse Ringers's avatar
Sietse Ringers committed
26
	KeyshareCancelled()
27
	KeyshareBlocked(manager irma.SchemeManagerIdentifier, duration int)
Sietse Ringers's avatar
Sietse Ringers committed
28
	KeyshareEnrollmentIncomplete(manager irma.SchemeManagerIdentifier)
29
	KeyshareEnrollmentDeleted(manager irma.SchemeManagerIdentifier)
30
31
	// In errors the manager may be nil, as not all keyshare errors have a clearly associated scheme manager
	KeyshareError(manager *irma.SchemeManagerIdentifier, err error)
Sietse Ringers's avatar
Sietse Ringers committed
32
33
	KeysharePin()
	KeysharePinOK()
Sietse Ringers's avatar
Sietse Ringers committed
34
35
36
}

type keyshareSession struct {
37
38
39
	sessionHandler  keyshareSessionHandler
	pinRequestor    KeysharePinRequestor
	builders        gabi.ProofBuilderList
40
	session         irma.IrmaSession
41
	conf            *irma.Configuration
42
	keyshareServers map[irma.SchemeManagerIdentifier]*keyshareServer
43
	keyshareServer  *keyshareServer // The one keyshare server in use in case of issuance
44
	transports      map[irma.SchemeManagerIdentifier]*irma.HTTPTransport
45
	state           *issuanceState
Sietse Ringers's avatar
Sietse Ringers committed
46
47
}

48
type keyshareServer struct {
49
50
51
52
53
54
	URL                     string              `json:"url"`
	Username                string              `json:"username"`
	Nonce                   []byte              `json:"nonce"`
	PrivateKey              *paillierPrivateKey `json:"keyPair"`
	SchemeManagerIdentifier irma.SchemeManagerIdentifier
	token                   string
55
56
}

57
type keyshareEnrollment struct {
Sietse Ringers's avatar
Sietse Ringers committed
58
59
	Username  string             `json:"username"`
	Pin       string             `json:"pin"`
Sietse Ringers's avatar
Sietse Ringers committed
60
	PublicKey *paillierPublicKey `json:"publicKey"`
61
	Email     *string            `json:"email"`
62
	Language  string             `json:"language"`
Sietse Ringers's avatar
Sietse Ringers committed
63
64
}

65
66
67
68
69
70
type keysharePinchange struct {
	Username string `json:"id"`
	Oldpin string   `json:"oldpin"`
	Newpin string   `json:"newpin"`
}

Sietse Ringers's avatar
Sietse Ringers committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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"`
}

91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// TODO enable this when updating protocol
//func (pki *publicKeyIdentifier) UnmarshalText(text []byte) error {
//	str := string(text)
//	index := strings.LastIndex(str, "-")
//	if index == -1 {
//		return errors.New("Invalid publicKeyIdentifier")
//	}
//	counter, err := strconv.Atoi(str[index+1:])
//	if err != nil {
//		return err
//	}
//	*pki = publicKeyIdentifier{Issuer: str[:index], Counter: uint(counter)}
//	return nil
//}
//
//func (pki *publicKeyIdentifier) MarshalText() (text []byte, err error) {
//	return []byte(fmt.Sprintf("%s-%d", pki.Issuer, pki.Counter)), nil
//}
Sietse Ringers's avatar
Sietse Ringers committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

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

const (
	kssUsernameHeader = "IRMA_Username"
	kssAuthHeader     = "IRMA_Authorization"
	kssAuthorized     = "authorized"
	kssTokenExpired   = "expired"
	kssPinSuccess     = "success"
	kssPinFailure     = "failure"
	kssPinError       = "error"
)

124
125
126
func newKeyshareServer(
	schemeManagerIdentifier irma.SchemeManagerIdentifier,
	privatekey *paillierPrivateKey,
127
	url string,
128
) (ks *keyshareServer, err error) {
Sietse Ringers's avatar
Sietse Ringers committed
129
	ks = &keyshareServer{
130
131
132
133
		Nonce:                   make([]byte, 32),
		URL:                     url,
		PrivateKey:              privatekey,
		SchemeManagerIdentifier: schemeManagerIdentifier,
Sietse Ringers's avatar
Sietse Ringers committed
134
	}
135
136
137
138
139
140
	_, err = rand.Read(ks.Nonce)
	return
}

func (ks *keyshareServer) HashedPin(pin string) string {
	hash := sha256.Sum256(append(ks.Nonce, []byte(pin)...))
141
142
143
144
	// We must be compatible with the old Android app here,
	// which uses Base64.encodeToString(hash, Base64.DEFAULT),
	// which appends a newline.
	return base64.StdEncoding.EncodeToString(hash[:]) + "\n"
145
}
Sietse Ringers's avatar
Sietse Ringers committed
146

Sietse Ringers's avatar
Sietse Ringers committed
147
148
149
150
151
152
153
154
// 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(
	sessionHandler keyshareSessionHandler,
	pin KeysharePinRequestor,
155
	builders gabi.ProofBuilderList,
156
	session irma.IrmaSession,
157
	conf *irma.Configuration,
158
	keyshareServers map[irma.SchemeManagerIdentifier]*keyshareServer,
159
	state *issuanceState,
Sietse Ringers's avatar
Sietse Ringers committed
160
161
) {
	ksscount := 0
162
	for managerID := range session.Identifiers().SchemeManagers {
163
		if conf.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
164
			ksscount++
165
166
			if _, enrolled := keyshareServers[managerID]; !enrolled {
				err := errors.New("Not enrolled to keyshare server of scheme manager " + managerID.String())
167
				sessionHandler.KeyshareError(&managerID, err)
Sietse Ringers's avatar
Sietse Ringers committed
168
169
170
171
				return
			}
		}
	}
172
	if _, issuing := session.(*irma.IssuanceRequest); issuing && ksscount > 1 {
Sietse Ringers's avatar
Sietse Ringers committed
173
		err := errors.New("Issuance session involving more than one keyshare servers are not supported")
174
		sessionHandler.KeyshareError(nil, err)
Sietse Ringers's avatar
Sietse Ringers committed
175
176
177
178
		return
	}

	ks := &keyshareSession{
179
180
181
		session:         session,
		builders:        builders,
		sessionHandler:  sessionHandler,
182
		transports:      map[irma.SchemeManagerIdentifier]*irma.HTTPTransport{},
183
		pinRequestor:    pin,
184
		conf:            conf,
185
		keyshareServers: keyshareServers,
186
		state:           state,
Sietse Ringers's avatar
Sietse Ringers committed
187
188
	}

189
	requestPin := false
Sietse Ringers's avatar
Sietse Ringers committed
190

191
	for managerID := range session.Identifiers().SchemeManagers {
192
		if !ks.conf.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
193
194
195
			continue
		}

196
		ks.keyshareServer = ks.keyshareServers[managerID]
197
		transport := irma.NewHTTPTransport(ks.keyshareServer.URL)
Sietse Ringers's avatar
Sietse Ringers committed
198
199
		transport.SetHeader(kssUsernameHeader, ks.keyshareServer.Username)
		transport.SetHeader(kssAuthHeader, ks.keyshareServer.token)
200
		ks.transports[managerID] = transport
Sietse Ringers's avatar
Sietse Ringers committed
201
202
203
204

		authstatus := &keyshareAuthorization{}
		err := transport.Post("users/isAuthorized", authstatus, "")
		if err != nil {
205
			ks.fail(managerID, err)
Sietse Ringers's avatar
Sietse Ringers committed
206
207
208
209
210
			return
		}
		switch authstatus.Status {
		case kssAuthorized: // nop
		case kssTokenExpired:
211
			requestPin = true
Sietse Ringers's avatar
Sietse Ringers committed
212
		default:
213
			ks.sessionHandler.KeyshareError(&managerID, errors.New("Keyshare server returned unrecognized authorization status"))
Sietse Ringers's avatar
Sietse Ringers committed
214
215
216
217
			return
		}
	}

218
	if requestPin {
Sietse Ringers's avatar
Sietse Ringers committed
219
		ks.sessionHandler.KeysharePin()
Sietse Ringers's avatar
Sietse Ringers committed
220
		ks.VerifyPin(-1)
221
222
	} else {
		ks.GetCommitments()
Sietse Ringers's avatar
Sietse Ringers committed
223
224
225
	}
}

226
227
228
func (ks *keyshareSession) fail(manager irma.SchemeManagerIdentifier, err error) {
	serr, ok := err.(*irma.SessionError)
	if ok {
Tomas's avatar
Tomas committed
229
230
		if serr.RemoteError != nil && len(serr.RemoteError.ErrorName) > 0 {
			switch serr.RemoteError.ErrorName {
231
232
			case "USER_NOT_FOUND":
				ks.sessionHandler.KeyshareEnrollmentDeleted(manager)
233
			case "USER_NOT_REGISTERED":
Sietse Ringers's avatar
Sietse Ringers committed
234
				ks.sessionHandler.KeyshareEnrollmentIncomplete(manager)
235
			case "USER_BLOCKED":
Tomas's avatar
Tomas committed
236
				duration, err := strconv.Atoi(serr.RemoteError.Message)
237
238
239
240
241
242
243
244
245
246
247
248
249
				if err != nil { // Not really clear what to do with duration, but should never happen anyway
					duration = -1
				}
				ks.sessionHandler.KeyshareBlocked(manager, duration)
			default:
				ks.sessionHandler.KeyshareError(&manager, err)
			}
		}
	} else {
		ks.sessionHandler.KeyshareError(&manager, err)
	}
}

Sietse Ringers's avatar
Sietse Ringers committed
250
251
252
// 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) {
253
	ks.pinRequestor.RequestPin(attempts, PinHandler(func(proceed bool, pin string) {
254
255
		if !proceed {
			ks.sessionHandler.KeyshareCancelled()
Sietse Ringers's avatar
Sietse Ringers committed
256
			return
257
		}
258
		success, attemptsRemaining, blocked, manager, err := ks.verifyPinAttempt(pin)
Sietse Ringers's avatar
Sietse Ringers committed
259
		if err != nil {
260
			ks.sessionHandler.KeyshareError(&manager, err)
Sietse Ringers's avatar
Sietse Ringers committed
261
262
263
			return
		}
		if blocked != 0 {
264
			ks.sessionHandler.KeyshareBlocked(manager, blocked)
Sietse Ringers's avatar
Sietse Ringers committed
265
266
267
			return
		}
		if success {
Sietse Ringers's avatar
Sietse Ringers committed
268
			ks.sessionHandler.KeysharePinOK()
Sietse Ringers's avatar
Sietse Ringers committed
269
270
271
272
273
			ks.GetCommitments()
			return
		}
		// Not successful but no error and not yet blocked: try again
		ks.VerifyPin(attemptsRemaining)
274
	}))
Sietse Ringers's avatar
Sietse Ringers committed
275
276
277
278
279
280
281
282
283
284
}

// 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.
285
286
287
288
func (ks *keyshareSession) verifyPinAttempt(pin string) (
	success bool, tries int, blocked int, manager irma.SchemeManagerIdentifier, err error) {
	for manager = range ks.session.Identifiers().SchemeManagers {
		if !ks.conf.SchemeManagers[manager].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
289
290
291
			continue
		}

292
293
		kss := ks.keyshareServers[manager]
		transport := ks.transports[manager]
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
323
324
		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)
			return
		case kssPinError:
			blocked, err = strconv.Atoi(pinresult.Message)
			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() {
325
	pkids := map[irma.SchemeManagerIdentifier][]*publicKeyIdentifier{}
Sietse Ringers's avatar
Sietse Ringers committed
326
327
328
329
330
331
	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()
332
		managerID := irma.NewIssuerIdentifier(pk.Issuer).SchemeManagerIdentifier()
333
		if !ks.conf.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
334
335
			continue
		}
336
337
		if _, contains := pkids[managerID]; !contains {
			pkids[managerID] = []*publicKeyIdentifier{}
Sietse Ringers's avatar
Sietse Ringers committed
338
		}
339
		pkids[managerID] = append(pkids[managerID], &publicKeyIdentifier{Issuer: pk.Issuer, Counter: pk.Counter})
Sietse Ringers's avatar
Sietse Ringers committed
340
341
342
343
	}

	// Now inform each keyshare server of with respect to which public keys
	// we want them to send us commitments
344
	for managerID := range ks.session.Identifiers().SchemeManagers {
345
		if !ks.conf.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
346
347
348
			continue
		}

349
		transport := ks.transports[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
350
		comms := &proofPCommitmentMap{}
351
		err := transport.Post("prove/getCommitments", comms, pkids[managerID])
Sietse Ringers's avatar
Sietse Ringers committed
352
		if err != nil {
353
			ks.sessionHandler.KeyshareError(&managerID, err)
Sietse Ringers's avatar
Sietse Ringers committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
			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() {
379
380
	_, issig := ks.session.(*irma.SignatureRequest)
	_, issuing := ks.session.(*irma.IssuanceRequest)
381
	challenge := ks.builders.Challenge(ks.session.GetContext(), ks.session.GetNonce(), issig)
Sietse Ringers's avatar
Sietse Ringers committed
382
383
384
385
386
387
	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 {
388
			ks.sessionHandler.KeyshareError(&ks.keyshareServer.SchemeManagerIdentifier, err)
Sietse Ringers's avatar
Sietse Ringers committed
389
390
391
392
393
		}
		kssChallenge = new(big.Int).SetBytes(bytes)
	}

	// Post the challenge, obtaining JWT's containing the ProofP's
394
	responses := map[irma.SchemeManagerIdentifier]string{}
395
	for managerID := range ks.session.Identifiers().SchemeManagers {
396
		transport, distributed := ks.transports[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
397
398
399
400
401
402
		if !distributed {
			continue
		}
		var jwt string
		err := transport.Post("prove/getResponse", &jwt, kssChallenge)
		if err != nil {
403
			ks.sessionHandler.KeyshareError(&managerID, err)
Sietse Ringers's avatar
Sietse Ringers committed
404
405
			return
		}
406
		responses[managerID] = jwt
Sietse Ringers's avatar
Sietse Ringers committed
407
408
409
410
411
412
413
414
	}

	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.
415
func (ks *keyshareSession) Finish(challenge *big.Int, responses map[irma.SchemeManagerIdentifier]string) {
Sietse Ringers's avatar
Sietse Ringers committed
416
	switch ks.session.(type) {
417
	case *irma.DisclosureRequest: // Can't use fallthrough in a type switch in go
418
		ks.finishDisclosureOrSigning(challenge, responses)
419
	case *irma.SignatureRequest: // So we have to do this in a separate method
420
		ks.finishDisclosureOrSigning(challenge, responses)
421
	case *irma.IssuanceRequest:
Sietse Ringers's avatar
Sietse Ringers committed
422
423
424
		// 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
425
		list, err := ks.builders.BuildDistributedProofList(challenge, nil)
Sietse Ringers's avatar
Sietse Ringers committed
426
		if err != nil {
427
			ks.sessionHandler.KeyshareError(&ks.keyshareServer.SchemeManagerIdentifier, err)
Sietse Ringers's avatar
Sietse Ringers committed
428
429
			return
		}
430
		message := &gabi.IssueCommitmentMessage{Proofs: list, Nonce2: ks.state.nonce2}
431
432
433
		for _, response := range responses {
			message.ProofPjwt = response
			break
Sietse Ringers's avatar
Sietse Ringers committed
434
		}
435
436
437
438
439
		// TODO for new protocol version
		//message.ProofPjwts = map[string]string{}
		//for manager, response := range responses {
		//	message.ProofPjwts[manager.String()] = response
		//}
Sietse Ringers's avatar
Sietse Ringers committed
440
441
442
443
		ks.sessionHandler.KeyshareDone(message)
	}
}

444
func (ks *keyshareSession) finishDisclosureOrSigning(challenge *big.Int, responses map[irma.SchemeManagerIdentifier]string) {
445
446
447
	proofPs := make([]*gabi.ProofP, len(ks.builders))
	for i, builder := range ks.builders {
		// Parse each received JWT
448
		managerID := irma.NewIssuerIdentifier(builder.PublicKey().Issuer).SchemeManagerIdentifier()
449
		if !ks.conf.SchemeManagers[managerID].Distributed() {
450
451
452
453
454
			continue
		}
		msg := struct {
			ProofP *gabi.ProofP
		}{}
455
		if err := irma.JwtDecode(responses[managerID], &msg); err != nil {
456
			ks.sessionHandler.KeyshareError(&managerID, err)
457
458
459
460
461
462
463
			return
		}

		// Decrypt the responses and populate a slice of ProofP's
		proofPs[i] = msg.ProofP
		bytes, err := ks.keyshareServer.PrivateKey.Decrypt(proofPs[i].SResponse.Bytes())
		if err != nil {
464
			ks.sessionHandler.KeyshareError(&managerID, err)
465
466
467
468
469
470
471
472
			return
		}
		proofPs[i].SResponse = new(big.Int).SetBytes(bytes)
	}

	// Create merged proofs and finish protocol
	list, err := ks.builders.BuildDistributedProofList(challenge, proofPs)
	if err != nil {
473
		ks.sessionHandler.KeyshareError(nil, err)
474
475
476
477
		return
	}
	ks.sessionHandler.KeyshareDone(list)
}