server.go 12.3 KB
Newer Older
Sietse Ringers's avatar
Sietse Ringers committed
1
2
3
4
// Package irmad is a server allowing IRMA verifiers, issuers or attribute-based signature
// applications (the requestor) to perform IRMA sessions with irmaclient instances (i.e. the IRMA
// app). It exposes a RESTful protocol with which the requestor can start and manage the session as
// well as HTTP endpoints for the irmaclient.
Sietse Ringers's avatar
Sietse Ringers committed
5
package requestorserver
6
7

import (
Sietse Ringers's avatar
Sietse Ringers committed
8
	"crypto/tls"
9
	"crypto/x509"
Sietse Ringers's avatar
Sietse Ringers committed
10
	"encoding/json"
11
	"encoding/pem"
12
	"fmt"
13
14
	"io/ioutil"
	"net/http"
15
	"time"
16

17
	"github.com/dgrijalva/jwt-go"
18
	"github.com/go-chi/chi"
Sietse Ringers's avatar
Sietse Ringers committed
19
	"github.com/go-chi/cors"
20
	"github.com/go-errors/errors"
21
	"github.com/privacybydesign/irmago"
Sietse Ringers's avatar
Sietse Ringers committed
22
	"github.com/privacybydesign/irmago/server"
23
	"github.com/privacybydesign/irmago/server/irmaserver"
24
	"github.com/sirupsen/logrus"
25
26
)

27
type Server struct {
28
29
	serv, clientserv *http.Server
	conf             *Configuration
30
	irmaserv         *irmaserver.Server
31
}
32

33
// Start the server. If successful then it will not return until Stop() is called.
34
35
36
func (s *Server) Start(config *Configuration) error {
	if s.conf.LogJSON {
		s.conf.Logger.WithField("configuration", s.conf).Debug("Configuration")
37
	} else {
38
39
		bts, _ := json.MarshalIndent(s.conf, "", "   ")
		s.conf.Logger.Debug("Configuration: ", string(bts), "\n")
40
	}
41

42
	// Start server(s)
43
44
	if s.conf.separateClientServer() {
		go s.startClientServer()
45
	}
46
	s.startRequestorServer()
47

48
	return nil
49
50
}

51
52
53
54
func (s *Server) startRequestorServer() {
	s.serv = &http.Server{}
	tlsConf, _ := s.conf.tlsConfig()
	s.startServer(s.serv, s.Handler(), "Server", s.conf.ListenAddress, s.conf.Port, tlsConf)
55
56
}

57
58
59
60
func (s *Server) startClientServer() {
	s.clientserv = &http.Server{}
	tlsConf, _ := s.conf.clientTlsConfig()
	s.startServer(s.clientserv, s.ClientHandler(), "Client server", s.conf.ClientListenAddress, s.conf.ClientPort, tlsConf)
61
62
}

63
func (s *Server) startServer(serv *http.Server, handler http.Handler, name, addr string, port int, tlsConf *tls.Config) {
64
	fulladdr := fmt.Sprintf("%s:%d", addr, port)
65
66
67
	s.conf.Logger.Info(name, " listening at ", fulladdr)
	serv.Addr = fulladdr
	serv.Handler = handler
Sietse Ringers's avatar
Sietse Ringers committed
68
69
	var err error
	if tlsConf != nil {
70
		serv.TLSConfig = tlsConf
71
		// Disable HTTP/2 (see package documentation of http): it breaks server side events :(
72
73
74
		serv.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
		s.conf.Logger.Info(name, " TLS enabled")
		err = serv.ListenAndServeTLS("", "")
Sietse Ringers's avatar
Sietse Ringers committed
75
	} else {
76
		err = serv.ListenAndServe()
Sietse Ringers's avatar
Sietse Ringers committed
77
78
	}
	if err != http.ErrServerClosed {
79
80
81
82
		_ = server.LogFatal(err)
	}
}

83
func (s *Server) Stop() error {
84
85
86
	var err1, err2 error

	// Even if closing serv fails, we want to try closing clientserv
87
88
89
	err1 = s.serv.Close()
	if s.clientserv != nil {
		err2 = s.clientserv.Close()
90
91
92
	}

	// Now check errors
93
	if err1 != nil && err1 != http.ErrServerClosed {
94
95
		return err1
	}
96
	if err2 != nil && err2 != http.ErrServerClosed {
97
98
99
100
101
		return err2
	}
	return nil
}

102
func New(config *Configuration) (*Server, error) {
103
	irmaserv, err := irmaserver.New(config.Configuration)
104
105
	if err != nil {
		return nil, err
106
	}
107
108
	if err := config.initialize(); err != nil {
		return nil, err
109
	}
110
111
112
113
	return &Server{
		conf:     config,
		irmaserv: irmaserv,
	}, nil
114
}
115

116
117
118
119
120
121
var corsOptions = cors.Options{
	AllowedOrigins: []string{"*"},
	AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "Cache-Control"},
	AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodDelete},
}

122
func (s *Server) ClientHandler() http.Handler {
123
	router := chi.NewRouter()
124
	router.Use(cors.New(corsOptions).Handler)
Sietse Ringers's avatar
Sietse Ringers committed
125

Sietse Ringers's avatar
Sietse Ringers committed
126
	router.Mount("/irma/", s.irmaserv.HandlerFunc())
127
128
129
130
131
	return router
}

// Handler returns a http.Handler that handles all IRMA requestor messages
// and IRMA client messages.
132
func (s *Server) Handler() http.Handler {
133
	router := chi.NewRouter()
134
	router.Use(cors.New(corsOptions).Handler)
135

136
	if !s.conf.separateClientServer() {
137
		// Mount server for irmaclient
Sietse Ringers's avatar
Sietse Ringers committed
138
		router.Mount("/irma/", s.irmaserv.HandlerFunc())
139
	}
140

141
	// Server routes
142
143
144
145
146
	router.Post("/session", s.handleCreate)
	router.Delete("/session/{token}", s.handleDelete)
	router.Get("/session/{token}/status", s.handleStatus)
	router.Get("/session/{token}/statusevents", s.handleStatusEvents)
	router.Get("/session/{token}/result", s.handleResult)
Sietse Ringers's avatar
Sietse Ringers committed
147
148

	// Routes for getting signed JWTs containing the session result. Only work if configuration has a private key
149
150
	router.Get("/session/{token}/result-jwt", s.handleJwtResult)
	router.Get("/session/{token}/getproof", s.handleJwtProofs) // irma_api_server-compatible JWT
151

152
	router.Get("/publickey", s.handlePublicKey)
153

154
	return router
155
156
}

157
func (s *Server) handleCreate(w http.ResponseWriter, r *http.Request) {
158
159
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
160
		s.conf.Logger.Error("Could not read session request HTTP POST body")
161
		_ = server.LogError(err)
Sietse Ringers's avatar
Sietse Ringers committed
162
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
163
164
		return
	}
165

Sietse Ringers's avatar
Sietse Ringers committed
166
167
168
	// Authenticate request: check if the requestor is known and allowed to submit requests.
	// We do this by feeding the HTTP POST details to all known authenticators, and see if
	// one of them is applicable and able to authenticate the request.
169
	var (
170
		rrequest  irma.RequestorRequest
171
172
173
174
175
176
		request   irma.SessionRequest
		requestor string
		rerr      *irma.RemoteError
		applies   bool
	)
	for _, authenticator := range authenticators {
177
		applies, rrequest, requestor, rerr = authenticator.Authenticate(r.Header, body)
178
179
180
181
182
		if applies || rerr != nil {
			break
		}
	}
	if rerr != nil {
183
		_ = server.LogError(rerr)
184
185
186
187
		server.WriteResponse(w, nil, rerr)
		return
	}
	if !applies {
188
		s.conf.Logger.Warnf("Session request uses unknown authentication method, HTTP headers: %s, HTTP POST body: %s",
189
			server.ToJson(r.Header), string(body))
Sietse Ringers's avatar
Sietse Ringers committed
190
		server.WriteError(w, server.ErrorInvalidRequest, "Request could not be authorized")
191
192
193
		return
	}

194
195
	// Authorize request: check if the requestor is allowed to verify or issue
	// the requested attributes or credentials
196
	request = rrequest.SessionRequest()
197
	if request.Action() == irma.ActionIssuing {
198
		allowed, reason := s.conf.CanIssue(requestor, request.(*irma.IssuanceRequest).Credentials)
199
		if !allowed {
200
			s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor, "id": reason}).
201
				Warn("Requestor not authorized to issue credential; full request: ", server.ToJson(request))
202
203
204
205
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
Sietse Ringers's avatar
Sietse Ringers committed
206
	disjunctions := request.ToDisclose()
207
	if len(disjunctions) > 0 {
208
		allowed, reason := s.conf.CanVerifyOrSign(requestor, request.Action(), disjunctions)
209
		if !allowed {
210
			s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor, "id": reason}).
211
				Warn("Requestor not authorized to verify attribute; full request: ", server.ToJson(request))
212
213
214
215
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
216
217
	if rrequest.Base().CallbackUrl != "" && s.conf.jwtPrivateKey == nil {
		s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor}).Warn("Requestor provided callbackUrl but no JWT private key is installed")
218
219
220
		server.WriteError(w, server.ErrorUnsupported, "")
		return
	}
221
222

	// Everything is authenticated and parsed, we're good to go!
223
	qr, _, err := s.irmaserv.StartSession(rrequest, s.doResultCallback)
224
	if err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
225
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
226
227
228
		return
	}

Sietse Ringers's avatar
Sietse Ringers committed
229
	server.WriteJson(w, qr)
230
231
}

232
233
func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
	res := s.irmaserv.GetSessionResult(chi.URLParam(r, "token"))
234
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
235
		server.WriteError(w, server.ErrorSessionUnknown, "")
236
237
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
238
	server.WriteJson(w, res.Status)
239
240
}

241
func (s *Server) handleStatusEvents(w http.ResponseWriter, r *http.Request) {
242
	token := chi.URLParam(r, "token")
243
244
	s.conf.Logger.WithFields(logrus.Fields{"session": token}).Debug("new client subscribed to server sent events")
	if err := s.irmaserv.SubscribeServerSentEvents(w, r, token); err != nil {
245
246
247
248
		server.WriteError(w, server.ErrorUnexpectedRequest, err.Error())
	}
}

249
250
func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request) {
	err := s.irmaserv.CancelSession(chi.URLParam(r, "token"))
251
252
253
254
255
	if err != nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
	}
}

256
257
func (s *Server) handleResult(w http.ResponseWriter, r *http.Request) {
	res := s.irmaserv.GetSessionResult(chi.URLParam(r, "token"))
258
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
259
		server.WriteError(w, server.ErrorSessionUnknown, "")
260
261
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
262
	server.WriteJson(w, res)
263
264
}

265
266
267
func (s *Server) handleJwtResult(w http.ResponseWriter, r *http.Request) {
	if s.conf.jwtPrivateKey == nil {
		s.conf.Logger.Warn("Session result JWT requested but no JWT private key is configured")
268
269
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
270
	}
271

272
	sessiontoken := chi.URLParam(r, "token")
273
	res := s.irmaserv.GetSessionResult(sessiontoken)
274
275
276
	if res == nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
		return
277
	}
278

279
	j, err := s.resultJwt(res)
280
	if err != nil {
281
		s.conf.Logger.Error("Failed to sign session result JWT")
282
		_ = server.LogError(err)
283
284
285
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
286
	server.WriteString(w, j)
287
288
}

289
290
291
func (s *Server) handleJwtProofs(w http.ResponseWriter, r *http.Request) {
	if s.conf.jwtPrivateKey == nil {
		s.conf.Logger.Warn("Session result JWT requested but no JWT private key is configured")
292
293
294
295
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
	}

296
	sessiontoken := chi.URLParam(r, "token")
297
	res := s.irmaserv.GetSessionResult(sessiontoken)
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
	if res == nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
		return
	}

	claims := jwt.MapClaims{}

	// Fill standard claims
	switch res.Type {
	case irma.ActionDisclosing:
		claims["subject"] = "verification_result"
	case irma.ActionSigning:
		claims["subject"] = "abs_result"
	default:
		if res == nil {
			server.WriteError(w, server.ErrorInvalidRequest, "")
			return
		}
	}
	claims["iat"] = time.Now().Unix()
318
319
	if s.conf.JwtIssuer != "" {
		claims["iss"] = s.conf.JwtIssuer
320
321
	}
	claims["status"] = res.Status
322
	validity := s.irmaserv.GetRequest(sessiontoken).Base().ResultJwtValidity
323
324
325
	if validity != 0 {
		claims["exp"] = time.Now().Unix() + int64(validity)
	}
326
327
328
329
330
331
332
333
334
335
336
337
338

	// Disclosed credentials and possibly signature
	m := make(map[irma.AttributeTypeIdentifier]string, len(res.Disclosed))
	for _, attr := range res.Disclosed {
		m[attr.Identifier] = attr.Value[""]
	}
	claims["attributes"] = m
	if res.Signature != nil {
		claims["signature"] = res.Signature
	}

	// Sign the jwt and return it
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
339
	resultJwt, err := token.SignedString(s.conf.jwtPrivateKey)
340
	if err != nil {
341
		s.conf.Logger.Error("Failed to sign session result JWT")
342
		_ = server.LogError(err)
343
344
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
345
	}
346
	server.WriteString(w, resultJwt)
347
}
348

349
350
func (s *Server) handlePublicKey(w http.ResponseWriter, r *http.Request) {
	if s.conf.jwtPrivateKey == nil {
351
352
353
354
		server.WriteError(w, server.ErrorUnsupported, "")
		return
	}

355
	bts, err := x509.MarshalPKIXPublicKey(&s.conf.jwtPrivateKey.PublicKey)
356
357
358
359
360
361
362
363
364
365
	if err != nil {
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
	pubBytes := pem.EncodeToMemory(&pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: bts,
	})
	_, _ = w.Write(pubBytes)
}
366

367
func (s *Server) resultJwt(sessionresult *server.SessionResult) (string, error) {
368
369
370
371
372
	claims := struct {
		jwt.StandardClaims
		*server.SessionResult
	}{
		StandardClaims: jwt.StandardClaims{
373
			Issuer:   s.conf.JwtIssuer,
374
375
376
377
378
			IssuedAt: time.Now().Unix(),
			Subject:  string(sessionresult.Type) + "_result",
		},
		SessionResult: sessionresult,
	}
379
	validity := s.irmaserv.GetRequest(sessionresult.Token).Base().ResultJwtValidity
380
381
382
383
384
385
	if validity != 0 {
		claims.ExpiresAt = time.Now().Unix() + int64(validity)
	}

	// Sign the jwt and return it
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
386
	return token.SignedString(s.conf.jwtPrivateKey)
387
388
}

389
390
391
func (s *Server) doResultCallback(result *server.SessionResult) {
	callbackUrl := s.irmaserv.GetRequest(result.Token).Base().CallbackUrl
	if callbackUrl == "" || s.conf.jwtPrivateKey == nil {
392
393
		return
	}
394
	s.conf.Logger.WithFields(logrus.Fields{"session": result.Token, "callbackUrl": callbackUrl}).Debug("POSTing session result")
395

396
	j, err := s.resultJwt(result)
397
398
399
400
401
402
403
404
	if err != nil {
		_ = server.LogError(errors.WrapPrefix(err, "Failed to create JWT for result callback", 0))
		return
	}

	var x string // dummy for the server's return value that we don't care about
	if err := irma.NewHTTPTransport(callbackUrl).Post("", &x, j); err != nil {
		// not our problem, log it and go on
405
		s.conf.Logger.Warn(errors.WrapPrefix(err, "Failed to POST session result to callback URL", 0))
406
407
	}
}