server.go 18.7 KB
Newer Older
1
package keyshareserver
2
3

import (
4
	"bytes"
5
6
7
8
9
10
11
12
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"
13
	"time"
14

15
	"github.com/jasonlvhit/gocron"
16
17
18
19
20
	"github.com/privacybydesign/gabi"
	"github.com/privacybydesign/gabi/big"
	irma "github.com/privacybydesign/irmago"
	"github.com/sirupsen/logrus"

21
	"github.com/privacybydesign/irmago/internal/common"
22
	"github.com/privacybydesign/irmago/internal/keysharecore"
23
24
25
26
27
28
29
	"github.com/privacybydesign/irmago/server"
	"github.com/privacybydesign/irmago/server/irmaserver"

	"github.com/go-chi/chi"
)

type SessionData struct {
30
	LastKeyID    irma.PublicKeyIdentifier // last used key, used in signing the issuance message
31
	LastCommitID uint64
32
	expiry       time.Time
33
34
35
}

type Server struct {
36
	// configuration
37
38
	conf *Configuration

39
	// external components
40
	core          *keysharecore.Core
41
42
	sessionserver *irmaserver.Server
	db            KeyshareDB
43
44

	// Scheduler used to clean sessions
45
46
	scheduler     *gocron.Scheduler
	stopScheduler chan<- bool
47

48
	// Session data, keeping track of current keyshare protocol session state for each user
49
50
51
52
53
54
55
	sessions    map[string]*SessionData
	sessionLock sync.Mutex
}

func New(conf *Configuration) (*Server, error) {
	var err error
	s := &Server{
56
57
58
		conf:      conf,
		sessions:  map[string]*SessionData{},
		scheduler: gocron.NewScheduler(),
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
	}

	// Do initial processing of configuration and create keyshare core
	s.core, err = processConfiguration(conf)
	if err != nil {
		return nil, err
	}

	// Load neccessary idemix keys into core, and ensure that future updates
	// to them are processed
	s.LoadIdemixKeys(conf.ServerConfiguration.IrmaConfiguration)
	conf.ServerConfiguration.IrmaConfiguration.UpdateListeners = append(
		conf.ServerConfiguration.IrmaConfiguration.UpdateListeners,
		s.LoadIdemixKeys)

74
	// Setup IRMA session server
75
76
77
78
79
	s.sessionserver, err = irmaserver.New(conf.ServerConfiguration)
	if err != nil {
		return nil, err
	}

80
81
	// Setup DB
	s.db = conf.DB
82

83
84
85
86
	// Setup session cache clearing
	s.scheduler.Every(10).Seconds().Do(s.clearSessions)
	s.stopScheduler = s.scheduler.Start()

87
88
89
	return s, nil
}

90
91
92
93
94
func (s *Server) Stop() {
	s.stopScheduler <- true
	s.sessionserver.Stop()
}

95
// clean up any expired sessions
96
97
98
99
100
101
102
103
104
105
106
func (s *Server) clearSessions() {
	now := time.Now()
	s.sessionLock.Lock()
	defer s.sessionLock.Unlock()
	for k, v := range s.sessions {
		if now.After(v.expiry) {
			delete(s.sessions, k)
		}
	}
}

107
108
func (s *Server) Handler() http.Handler {
	router := chi.NewRouter()
109
110
111
112
113
114

	if s.conf.Verbose >= 2 {
		opts := server.LogOptions{Response: true, Headers: true, From: false, EncodeBinary: true}
		router.Use(server.LogMiddleware("keyshare-app", opts))
	}

115
	// Registration
116
	router.Post("/client/register", s.handleRegister)
117
118

	// Pin and login
119
120
121
	router.Post("/users/isAuthorized", s.handleValidate)
	router.Post("/users/verify/pin", s.handleVerifyPin)
	router.Post("/users/change/pin", s.handleChangePin)
122
123

	// Keyshare sessions
124
125
	router.Post("/prove/getCommitments", s.handleCommitments)
	router.Post("/prove/getResponse", s.handleResponse)
126

127
	// IRMA server for issuing myirma credential during registration
128
129
130
131
	router.Mount("/irma/", s.sessionserver.HandlerFunc())
	return router
}

132
// On configuration changes, inform the keyshare core of any
133
// new IRMA issuer public keys.
134
135
func (s *Server) LoadIdemixKeys(conf *irma.Configuration) {
	for _, issuer := range conf.Issuers {
136
		keyIDs, err := conf.PublicKeyIndices(issuer.Identifier())
137
		if err != nil {
138
			s.conf.Logger.WithFields(logrus.Fields{"issuer": issuer, "error": err}).Warn("Could not find keyIDs for issuer")
139
140
			continue
		}
141
		for _, id := range keyIDs {
142
143
			key, err := conf.PublicKey(issuer.Identifier(), id)
			if err != nil {
144
				s.conf.Logger.WithFields(logrus.Fields{"keyID": id, "error": err}).Warn("Could not fetch public key for issuer")
145
146
147
148
149
150
151
				continue
			}
			s.core.DangerousAddTrustedPublicKey(irma.PublicKeyIdentifier{Issuer: issuer.Identifier(), Counter: uint(id)}, key)
		}
	}
}

152
// /prove/getCommitments
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
func (s *Server) handleCommitments(w http.ResponseWriter, r *http.Request) {
	// Read keys
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	var keys []irma.PublicKeyIdentifier
	err = json.Unmarshal(body, &keys)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not parse request body")
		s.conf.Logger.WithField("body", body).Debug("Malformed request data")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	if len(keys) == 0 {
		s.conf.Logger.Info("Malformed request: no keys over which to commit specified")
		server.WriteError(w, server.ErrorInvalidRequest, "No key specified")
		return
	}

	// Extract username and authorization from request
	username := r.Header.Get("X-IRMA-Keyshare-Username")
	authorization := r.Header.Get("Authorization")
178
179
180
	if strings.HasPrefix(authorization, "Bearer ") {
		authorization = authorization[7:]
	}
181
182
183
184
185
186
187
188

	user, err := s.db.User(username)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"username": username, "error": err}).Warn("User not found in db")
		server.WriteError(w, server.ErrorUserNotRegistered, err.Error())
		return
	}

189
	// Generate commitments
190
	commitments, commitID, err := s.core.GenerateCommitments(user.Data().Coredata, authorization, keys)
191
192
193
194
195
196
197
198
	if err != nil {
		s.conf.Logger.WithField("error", err).Warn("Could not generate commitments for request")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}

	// Prepare output message format
	mappedCommitments := map[string]*gabi.ProofPCommitment{}
199
200
	for i, keyID := range keys {
		keyIDV, err := keyID.MarshalText()
201
		if err != nil {
202
			s.conf.Logger.WithFields(logrus.Fields{"keyid": keyID, "error": err}).Error("Could not convert key identifier to string")
203
204
205
			server.WriteError(w, server.ErrorInternal, err.Error())
			return
		}
206
		mappedCommitments[string(keyIDV)] = commitments[i]
207
208
209
210
211
212
213
	}

	// Store needed data for later requests.
	s.sessionLock.Lock()
	if _, ok := s.sessions[username]; !ok {
		s.sessions[username] = &SessionData{}
	}
214
215
	s.sessions[username].LastCommitID = commitID
	s.sessions[username].LastKeyID = keys[0]
216
	s.sessions[username].expiry = time.Now().Add(10 * time.Second)
217
218
219
220
221
222
	s.sessionLock.Unlock()

	// And send response
	server.WriteJson(w, proofPCommitmentMap{Commitments: mappedCommitments})
}

223
// /prove/getResponse
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
func (s *Server) handleResponse(w http.ResponseWriter, r *http.Request) {
	// Read challenge
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	challenge := new(big.Int)
	err = json.Unmarshal(body, challenge)
	if err != nil {
		s.conf.Logger.Info("Malformed request: could not parse challenge")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}

	// Extract username and authorization from request
	username := r.Header.Get("X-IRMA-Keyshare-Username")
	authorization := r.Header.Get("Authorization")
243
244
245
	if strings.HasPrefix(authorization, "Bearer ") {
		authorization = authorization[7:]
	}
246
247
248
249
250
251
252
253
254
255

	// Fetch user
	user, err := s.db.User(username)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"username": username, "error": err}).Warn("Could not find user in db")
		server.WriteError(w, server.ErrorUserNotRegistered, err.Error())
		return
	}

	// verify access (avoids leaking information to unauthorized callers)
256
	err = s.core.ValidateJWT(user.Data().Coredata, authorization)
257
258
259
260
261
262
	if err != nil {
		s.conf.Logger.WithField("error", err).Warn("Could not generate keyshare response")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}

David Venhoek's avatar
David Venhoek committed
263
264
265
266
267
268
269
	// Indicate activity on user account
	err = s.db.SetSeen(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not mark user as seen recently")
		// Do not send to user
	}

270
271
272
273
274
275
276
277
278
279
	// Get data from session
	s.sessionLock.Lock()
	sessionData, ok := s.sessions[username]
	s.sessionLock.Unlock()
	if !ok {
		s.conf.Logger.Warn("Request for response without previous call to get commitments")
		server.WriteError(w, server.ErrorInvalidRequest, "Missing previous call to getCommitments")
		return
	}

280
281
282
283
284
285
286
287
	// Make log entry
	err = s.db.AddLog(user, IrmaSession, nil)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}

288
	proofResponse, err := s.core.GenerateResponse(user.Data().Coredata, authorization, sessionData.LastCommitID, challenge, sessionData.LastKeyID)
289
290
291
292
293
294
295
296
297
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not generate response for request")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}

	server.WriteString(w, proofResponse)
}

298
// /users/isAuthorized
299
300
301
302
func (s *Server) handleValidate(w http.ResponseWriter, r *http.Request) {
	// Extract username and authorization from request
	username := r.Header.Get("X-IRMA-Keyshare-Username")
	authorization := r.Header.Get("Authorization")
303
304
305
	if strings.HasPrefix(authorization, "Bearer ") {
		authorization = authorization[7:]
	}
306

307
	// Fetch user
308
309
310
311
312
313
314
	user, err := s.db.User(username)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"username": username, "error": err}).Warn("Could not find user in db")
		server.WriteError(w, server.ErrorUserNotRegistered, err.Error())
		return
	}

315
	// Validate jwt
316
	err = s.core.ValidateJWT(user.Data().Coredata, authorization)
317
318
319
320
321
322
323
	if err != nil {
		server.WriteJson(w, &keyshareAuthorization{Status: "expired", Candidates: []string{"pin"}})
	} else {
		server.WriteJson(w, &keyshareAuthorization{Status: "authorized", Candidates: []string{"pin"}})
	}
}

324
// /users/verify/pin
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
func (s *Server) handleVerifyPin(w http.ResponseWriter, r *http.Request) {
	// Extract request
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	var msg keysharePinMessage
	err = json.Unmarshal(body, &msg)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"error": err}).Info("Malformed request: could not parse request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}

	// Fetch user
	user, err := s.db.User(msg.Username)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"username": msg.Username, "error": err}).Warn("Could not find user in db")
		server.WriteError(w, server.ErrorUserNotRegistered, "")
		return
	}

349
350
	// And verify pin (checking that we are allowed to do this)
	ok, tries, wait, err := s.db.ReservePincheck(user)
351
	if err != nil {
352
353
354
355
356
		s.conf.Logger.WithField("error", err).Error("Could not reserve pin check slot")
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}
	if !ok {
357
358
359
360
361
362
		err = s.db.AddLog(user, PinCheckRefused, nil)
		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
			server.WriteError(w, server.ErrorInternal, err.Error())
			return
		}
363
364
365
		server.WriteJson(w, keysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)})
		return
	}
366
	jwtt, err := s.core.ValidatePin(user.Data().Coredata, msg.Pin, msg.Username)
367
	if err == keysharecore.ErrInvalidPin {
368
369
370
371
372
373
		err = s.db.AddLog(user, PinCheckFailed, tries)
		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
			server.WriteError(w, server.ErrorInternal, err.Error())
			return
		}
374
		if tries == 0 {
375
376
377
378
379
380
			err = s.db.AddLog(user, PinCheckBlocked, wait)
			if err != nil {
				s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
				server.WriteError(w, server.ErrorInternal, err.Error())
				return
			}
381
382
383
384
385
386
387
			server.WriteJson(w, keysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)})
		} else {
			server.WriteJson(w, keysharePinStatus{Status: "failure", Message: fmt.Sprintf("%v", tries)})
		}
	} else if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not validate pin")
		server.WriteError(w, server.ErrorInternal, err.Error())
388
	} else {
389
390
391
392
393
		err = s.db.ClearPincheck(user)
		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not reset users pin check logic")
			// Do not send to user
		}
David Venhoek's avatar
David Venhoek committed
394
395
396
397
398
399
400
401

		// Indicate activity on user account
		err = s.db.SetSeen(user)
		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not indicate user activity")
			// Do not send to user
		}

402
		err = s.db.AddLog(user, PinCheckSuccess, nil)
403
404
405
406
407
408
		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
			server.WriteError(w, server.ErrorInternal, err.Error())
			return
		}

409
410
411
412
		server.WriteJson(w, keysharePinStatus{Status: "success", Message: jwtt})
	}
}

413
// /users/change/pin
414
415
416
417
418
419
420
421
func (s *Server) handleChangePin(w http.ResponseWriter, r *http.Request) {
	// Extract request
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, "could not read request body")
		return
	}
422
	var msg keyshareChangePin
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
	err = json.Unmarshal(body, &msg)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not parse request body")
		server.WriteError(w, server.ErrorInvalidRequest, "Invalid request")
		return
	}

	// Fetch user
	user, err := s.db.User(msg.Username)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"username": msg.Username, "error": err}).Warn("Could not find user in db")
		server.WriteError(w, server.ErrorUserNotRegistered, "")
		return
	}

438
439
	// And change pin, checking that we are allowed to do this
	ok, tries, wait, err := s.db.ReservePincheck(user)
440
	if err != nil {
441
442
		s.conf.Logger.WithField("error", err).Error("Could not reserve pin check slot")
		server.WriteError(w, server.ErrorInternal, err.Error())
443
444
		return
	}
445
446
447
448
	if !ok {
		server.WriteJson(w, keysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)})
		return
	}
449
	user.Data().Coredata, err = s.core.ChangePin(user.Data().Coredata, msg.OldPin, msg.NewPin)
450
	if err == keysharecore.ErrInvalidPin {
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
		if tries == 0 {
			server.WriteJson(w, keysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)})
		} else {
			server.WriteJson(w, keysharePinStatus{Status: "failure", Message: fmt.Sprintf("%v", tries)})
		}
		return
	} else if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not change pin")
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}
	err = s.db.ClearPincheck(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not reset users pin check logic")
		// Do not send to user
	}
467
468
469
470
471
472
473
474
475
476
477
478
479

	// Write user back
	err = s.db.UpdateUser(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not write updated user to database")
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}

	// And return success
	server.WriteJson(w, keysharePinStatus{Status: "success"})
}

480
// /client/register
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
	// Extract request
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, "could not read request body")
		return
	}
	var msg keyshareEnrollment
	err = json.Unmarshal(body, &msg)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not parse request body")
		server.WriteError(w, server.ErrorInvalidRequest, "Invalid request")
		return
	}

	// Generate keyshare server account
	username := generateUsername()
	coredata, err := s.core.GenerateKeyshareSecret(msg.Pin)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not register user")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
505
	user, err := s.db.NewUser(KeyshareUserData{Username: username, Language: msg.Language, Coredata: coredata})
506
507
508
509
510
511
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not store new user in database")
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}

512
	// Send email if user specified email address
513
	if msg.Email != nil && *msg.Email != "" && s.conf.EmailServer != "" {
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
		// Fetch template and configuration data for users language, falling back if needed
		template, ok := s.conf.RegistrationEmailTemplates[msg.Language]
		if !ok {
			template = s.conf.RegistrationEmailTemplates[s.conf.DefaultLanguage]
		}
		verificationBaseURL, ok := s.conf.VerificationURL[msg.Language]
		if !ok {
			verificationBaseURL = s.conf.VerificationURL[s.conf.DefaultLanguage]
		}
		subject, ok := s.conf.RegistrationEmailSubject[msg.Language]
		if !ok {
			subject = s.conf.RegistrationEmailSubject[s.conf.DefaultLanguage]
		}

		// Generate token
529
		token := common.NewSessionToken()
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555

		// Add it to the database
		err = s.db.AddEmailVerification(user, *msg.Email, token)
		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not add email verification record to user")
			server.WriteError(w, server.ErrorInternal, err.Error())
			return
		}

		// Build message
		var emsg bytes.Buffer
		err = template.Execute(&emsg, map[string]string{"VerificationURL": verificationBaseURL + token})
		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not generate email verifcation mail")
			server.WriteError(w, server.ErrorInternal, err.Error())
			return
		}

		// And send it
		err = server.SendHTMLMail(
			s.conf.EmailServer,
			s.conf.EmailAuth,
			s.conf.EmailFrom,
			*msg.Email,
			subject,
			emsg.Bytes())
556
557
558
559
560
561

		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not send email verifiation mail")
			server.WriteError(w, server.ErrorInternal, err.Error())
			return
		}
562
563
	}

564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
	// Setup and return issuance session for keyshare credential.
	request := irma.NewIssuanceRequest([]*irma.CredentialRequest{
		{
			CredentialTypeID: irma.NewCredentialTypeIdentifier(s.conf.KeyshareCredential),
			Attributes: map[string]string{
				s.conf.KeyshareAttribute: username,
			},
		}})
	sessionptr, _, err := s.sessionserver.StartSession(request, nil)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not start keyshare credential issuance sessions")
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}
	server.WriteResponse(w, sessionptr, nil)
}

// Generate a base62 "username".
//  this is a direct port of what the old java server uses.
func generateUsername() string {
	bts := make([]byte, 8)
	_, err := rand.Read(bts)
	if err != nil {
		panic(err)
	}
	raw := make([]byte, 12)
	base64.StdEncoding.Encode(raw, bts)
	return strings.ReplaceAll(
		strings.ReplaceAll(
			strings.ReplaceAll(
				string(raw),
				"+",
				""),
			"/",
			""),
		"=",
		"")
}