server.go 10.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package keyshareServerCore

import (
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"

	"github.com/privacybydesign/gabi"
	"github.com/privacybydesign/gabi/big"
	irma "github.com/privacybydesign/irmago"
	"github.com/sirupsen/logrus"

	"github.com/privacybydesign/irmago/keyshareCore"
	"github.com/privacybydesign/irmago/server"
	"github.com/privacybydesign/irmago/server/irmaserver"

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

type SessionData struct {
	LastKeyid    irma.PublicKeyIdentifier
	LastCommitID uint64
}

type Server struct {
	conf *Configuration

	core          *keyshareCore.KeyshareCore
	sessionserver *irmaserver.Server
	db            KeyshareDB

	sessions    map[string]*SessionData
	sessionLock sync.Mutex
}

func New(conf *Configuration) (*Server, error) {
	var err error
	s := &Server{
		conf:     conf,
		sessions: map[string]*SessionData{},
	}

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

	// Setup irma session server
	s.sessionserver, err = irmaserver.New(conf.ServerConfiguration)
	if err != nil {
		return nil, err
	}

	// Setup DB (TODO: make configurable)
	s.db = NewMemoryDatabase()

	return s, nil
}

func (s *Server) Handler() http.Handler {
	router := chi.NewRouter()
	router.Use(middleware.Logger)
	router.Post("/api/v1/client/register", s.handleRegister)
	router.Post("/api/v1/users/isAuthorized", s.handleValidate)
	router.Post("/api/v1/users/verify/pin", s.handleVerifyPin)
	router.Post("/api/v1/prove/getCommitments", s.handleCommitments)
	router.Post("/api/v1/prove/getResponse", s.handleResponse)
	router.Mount("/irma/", s.sessionserver.HandlerFunc())
	return router
}

func (s *Server) LoadIdemixKeys(conf *irma.Configuration) {
	fmt.Println("load called")
	for _, issuer := range conf.Issuers {
		keyIds, err := conf.PublicKeyIndices(issuer.Identifier())
		if err != nil {
			s.conf.Logger.WithFields(logrus.Fields{"issuer": issuer, "error": err}).Warn("Could not find key ids for issuer")
			continue
		}
		for _, id := range keyIds {
			key, err := conf.PublicKey(issuer.Identifier(), id)
			if err != nil {
				s.conf.Logger.WithFields(logrus.Fields{"keyid": id, "error": err}).Warn("Could not fetch public key for issuer")
				continue
			}
			s.core.DangerousAddTrustedPublicKey(irma.PublicKeyIdentifier{Issuer: issuer.Identifier(), Counter: uint(id)}, key)
		}
	}
}

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
	}
	fmt.Println(string(body))
	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")

	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
	}

	// TODO: block check
	commitments, commitId, err := s.core.GenerateCommitments(user.Coredata, authorization, keys)
	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{}
	for i, keyid := range keys {
		keyidV, err := keyid.MarshalText()
		if err != nil {
			s.conf.Logger.WithFields(logrus.Fields{"keyid": keyid, "error": err}).Error("Could not convert key identifier to string")
			server.WriteError(w, server.ErrorInternal, err.Error())
			return
		}
		mappedCommitments[string(keyidV)] = commitments[i]
	}

	// Store needed data for later requests.
	s.sessionLock.Lock()
	if _, ok := s.sessions[username]; !ok {
		s.sessions[username] = &SessionData{}
	}
	s.sessions[username].LastCommitID = commitId
	s.sessions[username].LastKeyid = keys[0]
	s.sessionLock.Unlock()

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

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

	// 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)
	err = s.core.ValidateJWT(user.Coredata, authorization)
	if err != nil {
		s.conf.Logger.WithField("error", err).Warn("Could not generate keyshare response")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}

	// 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
	}

	proofResponse, err := s.core.GenerateResponse(user.Coredata, authorization, sessionData.LastCommitID, challenge, sessionData.LastKeyid)
	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)
}

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

	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
	}

	// TODO: Block check

	err = s.core.ValidateJWT(user.Coredata, authorization)
	if err != nil {
		server.WriteJson(w, &keyshareAuthorization{Status: "expired", Candidates: []string{"pin"}})
	} else {
		server.WriteJson(w, &keyshareAuthorization{Status: "authorized", Candidates: []string{"pin"}})
	}
}

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
	}

	// And verify pin
	// TODO: Count tries, deal with (temp) block
	jwtt, err := s.core.ValidatePin(user.Coredata, msg.Pin, msg.Username)
	if err != nil {
		fmt.Println(err)
		server.WriteJson(w, keysharePinStatus{Status: "failure", Message: err.Error()})
	} else {
		server.WriteJson(w, keysharePinStatus{Status: "success", Message: jwtt})
	}
}

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
	}
	err = s.db.NewUser(KeyshareUser{Username: username, Coredata: coredata})
	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
	}

	// 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),
				"+",
				""),
			"/",
			""),
		"=",
		"")
}