keyshare.go 13.9 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"

10
	"github.com/credentials/irmago"
Sietse Ringers's avatar
Sietse Ringers committed
11
	"github.com/go-errors/errors"
Sietse Ringers's avatar
Sietse Ringers committed
12
	"github.com/mhe/gabi"
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()
Sietse Ringers's avatar
Sietse Ringers committed
27
28
	KeyshareBlocked(duration int)
	KeyshareError(err error)
Sietse Ringers's avatar
Sietse Ringers committed
29
30
	KeysharePin()
	KeysharePinOK()
Sietse Ringers's avatar
Sietse Ringers committed
31
32
33
}

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

45
type keyshareServer struct {
Sietse Ringers's avatar
Sietse Ringers committed
46
47
48
49
	URL        string              `json:"url"`
	Username   string              `json:"username"`
	Nonce      []byte              `json:"nonce"`
	PrivateKey *paillierPrivateKey `json:"keyPair"`
Sietse Ringers's avatar
Sietse Ringers committed
50
	token      string
51
52
}

53
type keyshareEnrollment struct {
Sietse Ringers's avatar
Sietse Ringers committed
54
55
	Username  string             `json:"username"`
	Pin       string             `json:"pin"`
Sietse Ringers's avatar
Sietse Ringers committed
56
57
58
	PublicKey *paillierPublicKey `json:"publicKey"`
}

Sietse Ringers's avatar
Sietse Ringers committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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"`
}

79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

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"
)

Sietse Ringers's avatar
Sietse Ringers committed
112
func newKeyshareServer(privatekey *paillierPrivateKey, url, email string) (ks *keyshareServer, err error) {
Sietse Ringers's avatar
Sietse Ringers committed
113
114
115
116
117
118
	ks = &keyshareServer{
		Nonce:      make([]byte, 32),
		URL:        url,
		Username:   email,
		PrivateKey: privatekey,
	}
119
120
121
122
123
124
	_, err = rand.Read(ks.Nonce)
	return
}

func (ks *keyshareServer) HashedPin(pin string) string {
	hash := sha256.Sum256(append(ks.Nonce, []byte(pin)...))
125
126
127
128
	// 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"
129
}
Sietse Ringers's avatar
Sietse Ringers committed
130

Sietse Ringers's avatar
Sietse Ringers committed
131
132
133
134
135
136
137
138
// 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,
139
	builders gabi.ProofBuilderList,
140
	session irma.IrmaSession,
141
	conf *irma.Configuration,
142
	keyshareServers map[irma.SchemeManagerIdentifier]*keyshareServer,
143
	state *issuanceState,
Sietse Ringers's avatar
Sietse Ringers committed
144
145
) {
	ksscount := 0
146
	for managerID := range session.Identifiers().SchemeManagers {
147
		if conf.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
148
			ksscount++
149
150
			if _, enrolled := keyshareServers[managerID]; !enrolled {
				err := errors.New("Not enrolled to keyshare server of scheme manager " + managerID.String())
Sietse Ringers's avatar
Sietse Ringers committed
151
152
153
154
155
				sessionHandler.KeyshareError(err)
				return
			}
		}
	}
156
	if _, issuing := session.(*irma.IssuanceRequest); issuing && ksscount > 1 {
Sietse Ringers's avatar
Sietse Ringers committed
157
158
159
160
161
162
		err := errors.New("Issuance session involving more than one keyshare servers are not supported")
		sessionHandler.KeyshareError(err)
		return
	}

	ks := &keyshareSession{
163
164
165
		session:         session,
		builders:        builders,
		sessionHandler:  sessionHandler,
166
		transports:      map[irma.SchemeManagerIdentifier]*irma.HTTPTransport{},
167
		pinRequestor:    pin,
168
		conf:            conf,
169
		keyshareServers: keyshareServers,
170
		state:           state,
Sietse Ringers's avatar
Sietse Ringers committed
171
172
	}

173
	requestPin := false
Sietse Ringers's avatar
Sietse Ringers committed
174

175
	for managerID := range session.Identifiers().SchemeManagers {
176
		if !ks.conf.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
177
178
179
			continue
		}

180
		ks.keyshareServer = ks.keyshareServers[managerID]
181
		transport := irma.NewHTTPTransport(ks.keyshareServer.URL)
Sietse Ringers's avatar
Sietse Ringers committed
182
183
		transport.SetHeader(kssUsernameHeader, ks.keyshareServer.Username)
		transport.SetHeader(kssAuthHeader, ks.keyshareServer.token)
184
		ks.transports[managerID] = transport
Sietse Ringers's avatar
Sietse Ringers committed
185
186
187
188
189
190
191
192
193
194

		authstatus := &keyshareAuthorization{}
		err := transport.Post("users/isAuthorized", authstatus, "")
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
			return
		}
		switch authstatus.Status {
		case kssAuthorized: // nop
		case kssTokenExpired:
195
			requestPin = true
Sietse Ringers's avatar
Sietse Ringers committed
196
		default:
Sietse Ringers's avatar
Sietse Ringers committed
197
			ks.sessionHandler.KeyshareError(errors.New("Keyshare server returned unrecognized authorization status"))
Sietse Ringers's avatar
Sietse Ringers committed
198
199
200
201
			return
		}
	}

202
	if requestPin {
Sietse Ringers's avatar
Sietse Ringers committed
203
		ks.sessionHandler.KeysharePin()
Sietse Ringers's avatar
Sietse Ringers committed
204
		ks.VerifyPin(-1)
205
206
	} else {
		ks.GetCommitments()
Sietse Ringers's avatar
Sietse Ringers committed
207
208
209
210
211
212
	}
}

// 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) {
213
	ks.pinRequestor.RequestPin(attempts, PinHandler(func(proceed bool, pin string) {
214
215
		if !proceed {
			ks.sessionHandler.KeyshareCancelled()
Sietse Ringers's avatar
Sietse Ringers committed
216
			return
217
		}
Sietse Ringers's avatar
Sietse Ringers committed
218
219
220
221
222
223
224
225
226
227
		success, attemptsRemaining, blocked, err := ks.verifyPinAttempt(pin)
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
			return
		}
		if blocked != 0 {
			ks.sessionHandler.KeyshareBlocked(blocked)
			return
		}
		if success {
Sietse Ringers's avatar
Sietse Ringers committed
228
			ks.sessionHandler.KeysharePinOK()
Sietse Ringers's avatar
Sietse Ringers committed
229
230
231
232
233
			ks.GetCommitments()
			return
		}
		// Not successful but no error and not yet blocked: try again
		ks.VerifyPin(attemptsRemaining)
234
	}))
Sietse Ringers's avatar
Sietse Ringers committed
235
236
237
238
239
240
241
242
243
244
245
}

// 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) {
246
	for managerID := range ks.session.Identifiers().SchemeManagers {
247
		if !ks.conf.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
248
249
250
			continue
		}

251
		kss := ks.keyshareServers[managerID]
252
		transport := ks.transports[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
		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() {
290
	pkids := map[irma.SchemeManagerIdentifier][]*publicKeyIdentifier{}
Sietse Ringers's avatar
Sietse Ringers committed
291
292
293
294
295
296
	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()
297
		managerID := irma.NewIssuerIdentifier(pk.Issuer).SchemeManagerIdentifier()
298
		if !ks.conf.SchemeManagers[managerID].Distributed() {
Sietse Ringers's avatar
Sietse Ringers committed
299
300
			continue
		}
301
302
		if _, contains := pkids[managerID]; !contains {
			pkids[managerID] = []*publicKeyIdentifier{}
Sietse Ringers's avatar
Sietse Ringers committed
303
		}
304
		pkids[managerID] = append(pkids[managerID], &publicKeyIdentifier{Issuer: pk.Issuer, Counter: pk.Counter})
Sietse Ringers's avatar
Sietse Ringers committed
305
306
307
308
	}

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

314
		transport := ks.transports[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
315
		comms := &proofPCommitmentMap{}
316
		err := transport.Post("prove/getCommitments", comms, pkids[managerID])
Sietse Ringers's avatar
Sietse Ringers committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
		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() {
344
345
	_, issig := ks.session.(*irma.SignatureRequest)
	_, issuing := ks.session.(*irma.IssuanceRequest)
346
	challenge := ks.builders.Challenge(ks.session.GetContext(), ks.session.GetNonce(), issig)
Sietse Ringers's avatar
Sietse Ringers committed
347
348
349
350
351
352
353
354
355
356
357
358
	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
359
	responses := map[irma.SchemeManagerIdentifier]string{}
360
	for managerID := range ks.session.Identifiers().SchemeManagers {
361
		transport, distributed := ks.transports[managerID]
Sietse Ringers's avatar
Sietse Ringers committed
362
363
364
365
366
367
368
369
370
		if !distributed {
			continue
		}
		var jwt string
		err := transport.Post("prove/getResponse", &jwt, kssChallenge)
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
			return
		}
371
		responses[managerID] = jwt
Sietse Ringers's avatar
Sietse Ringers committed
372
373
374
375
376
377
378
379
	}

	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.
380
func (ks *keyshareSession) Finish(challenge *big.Int, responses map[irma.SchemeManagerIdentifier]string) {
Sietse Ringers's avatar
Sietse Ringers committed
381
	switch ks.session.(type) {
382
	case *irma.DisclosureRequest: // Can't use fallthrough in a type switch in go
383
		ks.finishDisclosureOrSigning(challenge, responses)
384
	case *irma.SignatureRequest: // So we have to do this in a separate method
385
		ks.finishDisclosureOrSigning(challenge, responses)
386
	case *irma.IssuanceRequest:
Sietse Ringers's avatar
Sietse Ringers committed
387
388
389
		// 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
390
		list, err := ks.builders.BuildDistributedProofList(challenge, nil)
Sietse Ringers's avatar
Sietse Ringers committed
391
392
393
394
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
			return
		}
395
		message := &gabi.IssueCommitmentMessage{Proofs: list, Nonce2: ks.state.nonce2}
396
397
398
		for _, response := range responses {
			message.ProofPjwt = response
			break
Sietse Ringers's avatar
Sietse Ringers committed
399
		}
400
401
402
403
404
		// 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
405
406
407
408
		ks.sessionHandler.KeyshareDone(message)
	}
}

409
func (ks *keyshareSession) finishDisclosureOrSigning(challenge *big.Int, responses map[irma.SchemeManagerIdentifier]string) {
410
411
412
	proofPs := make([]*gabi.ProofP, len(ks.builders))
	for i, builder := range ks.builders {
		// Parse each received JWT
413
		managerID := irma.NewIssuerIdentifier(builder.PublicKey().Issuer).SchemeManagerIdentifier()
414
		if !ks.conf.SchemeManagers[managerID].Distributed() {
415
416
417
418
419
			continue
		}
		msg := struct {
			ProofP *gabi.ProofP
		}{}
420
		if err := irma.JwtDecode(responses[managerID], &msg); err != nil {
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
			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].SResponse.Bytes())
		if err != nil {
			ks.sessionHandler.KeyshareError(err)
			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 {
		ks.sessionHandler.KeyshareError(err)
		return
	}
	ks.sessionHandler.KeyshareDone(list)
}