http.go 16.8 KB
Newer Older
ale's avatar
ale committed
1 2
package server

3
//go:generate python sri.py templates/*.html
ale's avatar
ale committed
4 5 6
//go:generate go-bindata --nocompress --pkg server static/... templates/...

import (
7
	"bytes"
ale's avatar
ale committed
8
	"context"
ale's avatar
ale committed
9
	"encoding/gob"
10
	"encoding/json"
ale's avatar
ale committed
11
	"fmt"
ale's avatar
ale committed
12
	"html/template"
ale's avatar
ale committed
13
	"io"
14
	"io/ioutil"
ale's avatar
ale committed
15 16 17
	"log"
	"net/http"
	"net/url"
18
	"os"
ale's avatar
ale committed
19 20 21 22 23 24 25
	"strings"
	"time"

	assetfs "github.com/elazarl/go-bindata-assetfs"
	"github.com/gorilla/csrf"
	"github.com/gorilla/mux"
	"github.com/gorilla/sessions"
ale's avatar
ale committed
26
	"github.com/rs/cors"
ale's avatar
ale committed
27 28 29

	"git.autistici.org/id/auth"
	authclient "git.autistici.org/id/auth/client"
30 31
	ksclient "git.autistici.org/id/keystore/client"

ale's avatar
ale committed
32
	"git.autistici.org/id/go-sso/httputil"
ale's avatar
ale committed
33 34 35 36 37 38
	"git.autistici.org/id/go-sso/server/device"
)

const authSessionKey = "_auth"

type authSession struct {
ale's avatar
ale committed
39
	*httputil.ExpiringSession
ale's avatar
ale committed
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

	// User name and other information (like group membership).
	Username string
	UserInfo *auth.UserInfo

	// Services the user has logged in to from this session.
	Services []string
}

// AddService adds a service to the current session (if it's not
// already there).
func (s *authSession) AddService(service string) {
	for _, svc := range s.Services {
		if svc == service {
			return
		}
	}
	s.Services = append(s.Services, service)
}

// By default, make users log in again after (almost) one day.
var defaultAuthSessionLifetime = 20 * time.Hour

func newAuthSession(ttl time.Duration, username string, userinfo *auth.UserInfo) *authSession {
	return &authSession{
ale's avatar
ale committed
65
		ExpiringSession: httputil.NewExpiringSession(ttl),
ale's avatar
ale committed
66 67 68 69 70 71 72 73 74
		Username:        username,
		UserInfo:        userinfo,
	}
}

func init() {
	gob.Register(&authSession{})
}

ale's avatar
ale committed
75 76 77 78 79 80 81 82 83 84 85 86 87
// Returns the URL of the login handler on the target service.
func serviceLoginCallback(service, destination, token string) string {
	v := make(url.Values)
	v.Set("t", token)
	v.Set("d", destination)
	return fmt.Sprintf("https://%ssso_login?%s", service, v.Encode())
}

// Returns the URL of the logout handler on the target service.
func serviceLogoutCallback(service string) string {
	return fmt.Sprintf("https://%ssso_logout", service)
}

ale's avatar
ale committed
88 89 90 91 92 93 94
// Server for the SSO protocol. Provides the HTTP interface to a
// LoginService.
type Server struct {
	authSessionStore    sessions.Store
	authSessionLifetime time.Duration
	loginHandler        *loginHandler
	loginService        *LoginService
ale's avatar
ale committed
95
	keystore            ksclient.Client
ale's avatar
ale committed
96
	keystoreGroups      []string
ale's avatar
ale committed
97
	csrfSecret          []byte
98
	renderer            *renderer
99
	urlPrefix           string
100
	homepageRedirectURL string
ale's avatar
ale committed
101
	allowedOrigins      []string
102 103 104 105

	// User-configurable static data that we serve from memory.
	siteLogo    *staticContent
	siteFavicon *staticContent
ale's avatar
ale committed
106 107
}

108 109 110 111 112 113 114 115
func sl2bl(sl []string) [][]byte {
	var out [][]byte
	for _, s := range sl {
		out = append(out, []byte(s))
	}
	return out
}

ale's avatar
ale committed
116 117
// New returns a new Server.
func New(loginService *LoginService, authClient authclient.Client, config *Config) (*Server, error) {
118
	urlPrefix := strings.TrimRight(config.URLPrefix, "/")
119 120
	sessionSecrets := sl2bl(config.SessionSecrets)
	store := sessions.NewCookieStore(sessionSecrets...)
ale's avatar
ale committed
121 122 123 124
	store.Options = &sessions.Options{
		HttpOnly: true,
		Secure:   true,
		MaxAge:   0,
125
		Path:     urlPrefix + "/",
ale's avatar
ale committed
126
	}
127

128
	renderer := newRenderer(config)
ale's avatar
ale committed
129 130 131 132
	s := &Server{
		authSessionLifetime: defaultAuthSessionLifetime,
		authSessionStore:    store,
		loginService:        loginService,
133
		urlPrefix:           urlPrefix,
134
		homepageRedirectURL: config.HomepageRedirectURL,
ale's avatar
ale committed
135
		allowedOrigins:      config.AllowedCORSOrigins,
136
		renderer:            renderer,
137 138 139
	}
	if config.CSRFSecret != "" {
		s.csrfSecret = []byte(config.CSRFSecret)
ale's avatar
ale committed
140 141 142 143 144
	}
	if config.AuthSessionLifetimeSeconds > 0 {
		s.authSessionLifetime = time.Duration(config.AuthSessionLifetimeSeconds) * time.Second
	}

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
	if config.SiteLogo != "" {
		siteLogo, err := loadStaticContent(config.SiteLogo)
		if err != nil {
			return nil, err
		}
		s.siteLogo = siteLogo
	}
	if config.SiteFavicon != "" {
		siteFavicon, err := loadStaticContent(config.SiteFavicon)
		if err != nil {
			return nil, err
		}
		s.siteFavicon = siteFavicon
	}

160 161 162 163 164
	if config.KeyStore != nil {
		ks, err := ksclient.New(config.KeyStore)
		if err != nil {
			return nil, err
		}
165
		log.Printf("keystore client enabled")
166
		s.keystore = ks
ale's avatar
ale committed
167
		s.keystoreGroups = config.KeyStoreEnableGroups
168 169
	}

ale's avatar
ale committed
170 171 172 173
	devMgr, err := device.New(config.DeviceManager)
	if err != nil {
		return nil, err
	}
ale's avatar
ale committed
174
	s.loginHandler = newLoginHandler(s.loginCallback, devMgr, authClient,
175 176
		config.AuthService, config.U2FAppID, config.URLPrefix,
		renderer, sessionSecrets...)
ale's avatar
ale committed
177 178 179 180

	return s, nil
}

ale's avatar
ale committed
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
func inAnyGroups(groups, ref []string) bool {
	for _, rr := range ref {
		for _, gg := range groups {
			if gg == rr {
				return true
			}
		}
	}
	return false
}

// We unlock the keystore if the following conditions are met:
// keystore_enable_groups is set, userinfo is not nil, and the groups match.
func (h *Server) maybeUnlockKeystore(ctx context.Context, username, password string, userinfo *auth.UserInfo) (bool, error) {
	if h.keystore == nil {
		return false, nil
	}

	var shard string
	if len(h.keystoreGroups) > 0 {
		if userinfo == nil {
			return false, nil
		}
		if !inAnyGroups(userinfo.Groups, h.keystoreGroups) {
			return false, nil
		}
		shard = userinfo.Shard
	}
	return true, h.keystore.Open(ctx, shard, username, password, int(h.authSessionLifetime.Seconds()))
}

212 213 214 215
func (h *Server) loginCallback(w http.ResponseWriter, req *http.Request, username, password string, userinfo *auth.UserInfo) error {
	// Open the keystore for this user with the password used to
	// authenticate. Set the TTL to the duration of the
	// authenticated session.
ale's avatar
ale committed
216 217 218 219
	decrypted, err := h.maybeUnlockKeystore(req.Context(), username, password, userinfo)
	if err != nil {
		log.Printf("failed to unlock keystore for user %s: %v", username, err)
		return err
220 221
	}

ale's avatar
ale committed
222 223 224 225
	var kmsg string
	if decrypted {
		kmsg = " (key unlocked)"
	}
ale's avatar
ale committed
226 227
	log.Printf("successful login for user %s%s", username, kmsg)

228
	// Create cookie-based session for the authenticated user.
ale's avatar
ale committed
229
	session := newAuthSession(h.authSessionLifetime, username, userinfo)
230
	httpSession, _ := h.authSessionStore.Get(req, authSessionKey) // nolint
231
	httpSession.Values["data"] = session
ale's avatar
ale committed
232 233 234
	return httpSession.Save(req, w)
}

235 236 237 238 239
func (h *Server) redirectToLogin(w http.ResponseWriter, req *http.Request) {
	http.Redirect(w, req, h.loginHandler.makeLoginURL(req), http.StatusFound)
}

func (h *Server) withAuth(f func(http.ResponseWriter, *http.Request, *authSession), authFail func(http.ResponseWriter, *http.Request)) http.Handler {
ale's avatar
ale committed
240 241 242 243 244 245
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		httpSession, err := h.authSessionStore.Get(req, authSessionKey)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
246 247
		session, ok := httpSession.Values["data"].(*authSession)
		if ok && session.Valid() {
ale's avatar
ale committed
248 249 250 251
			f(w, req, session)
			return
		}
		httpSession.Options.MaxAge = -1
252
		delete(httpSession.Values, "data")
253 254 255
		if err := httpSession.Save(req, w); err != nil {
			log.Printf("error saving session: %v", err)
		}
256
		authFail(w, req)
ale's avatar
ale committed
257 258 259
	})
}

260 261 262
// Token signing handler. Authorizes an authenticated user to a service by
// signing a token with the user's identity. The client is redirected back to
// the original service, with the signed token.
ale's avatar
ale committed
263 264
func (h *Server) handleHomepage(w http.ResponseWriter, req *http.Request, session *authSession) {
	// Extract the authorization request parameters from the HTTP
265 266 267 268 269 270
	// request query args.
	//
	// *NOTE*: we do not want to parse the request body, in case
	// it is a POST request redirected from a 307, so we do not
	// call req.FormValue() but look directly into request.URL
	// instead.
ale's avatar
ale committed
271
	username := session.Username
272 273 274 275
	service := req.URL.Query().Get("s")
	destination := req.URL.Query().Get("d")
	nonce := req.URL.Query().Get("n")
	groupsStr := req.URL.Query().Get("g")
ale's avatar
ale committed
276

277 278 279 280 281 282 283 284 285 286 287 288 289
	// If the above parameters are unset, we're probably faced with a user
	// that reached this URL by other means. Redirect them to the
	// configured homepageRedirectURL, or at least return a slightly more
	// user-friendly error.
	if service == "" || destination == "" {
		if h.homepageRedirectURL != "" {
			http.Redirect(w, req, h.homepageRedirectURL, http.StatusFound)
		} else {
			http.Error(w, "You are not supposed to reach this page directly. Use the back button in your browser instead.", http.StatusBadRequest)
		}
		return
	}

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
	// Compute the intersection of the user's groups and the
	// requested groups, to obtain the group memberships to grant.
	var groups []string
	if groupsStr != "" {
		reqGroups := strings.Split(groupsStr, ",")
		if len(reqGroups) > 0 && session.UserInfo != nil {
			groups = intersectGroups(reqGroups, session.UserInfo.Groups)
			// We only make this check here as a convenience to
			// the user (we may be able to show a nicer UI): the
			// actual group ACL must be applied on the destination
			// service, because the 'g' parameter is untrusted at
			// this stage.
			if len(groups) == 0 {
				http.Error(w, "Forbidden", http.StatusForbidden)
				return
			}
		}
	}

ale's avatar
ale committed
309 310 311
	// Make the authorization request.
	token, err := h.loginService.Authorize(username, service, destination, nonce, groups)
	if err != nil {
312
		log.Printf("auth error: %v: user=%s service=%s destination=%s nonce=%s groups=%s", err, username, service, destination, nonce, groupsStr)
ale's avatar
ale committed
313 314 315 316 317
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	session.AddService(service)
318 319 320
	if err := sessions.Save(req, w); err != nil {
		log.Printf("error saving session: %v", err)
	}
ale's avatar
ale committed
321 322

	// Redirect to service callback.
ale's avatar
ale committed
323
	callbackURL := serviceLoginCallback(service, destination, token)
ale's avatar
ale committed
324 325 326
	http.Redirect(w, req, callbackURL, http.StatusFound)
}

327 328 329 330
func (h *Server) alreadyLoggedOut(w http.ResponseWriter, req *http.Request) {
	http.Error(w, "You do not seem to be logged in", http.StatusBadRequest)
}

ale's avatar
ale committed
331
type logoutServiceInfo struct {
332 333
	URL  string `json:"url"`
	Name string `json:"name"`
ale's avatar
ale committed
334 335 336 337 338 339 340 341 342 343 344
}

func (h *Server) handleLogout(w http.ResponseWriter, req *http.Request, session *authSession) {
	var svcs []logoutServiceInfo
	for _, svc := range session.Services {
		svcs = append(svcs, logoutServiceInfo{
			Name: svc,
			URL:  serviceLogoutCallback(svc),
		})
	}

345
	svcJSON, _ := json.Marshal(svcs) // nolint
ale's avatar
ale committed
346
	data := map[string]interface{}{
347 348
		"Services":             svcs,
		"ServicesJSON":         string(svcJSON),
349
		"IncludeLogoutScripts": true,
ale's avatar
ale committed
350
	}
351

352 353 354 355 356 357 358 359 360 361 362 363 364 365
	// Clear the local session. Ignore errors.
	httpSession, _ := h.authSessionStore.Get(req, authSessionKey) // nolint
	delete(httpSession.Values, "data")
	httpSession.Options.MaxAge = -1
	httpSession.Save(req, w) // nolint

	// Close the keystore.
	if h.keystore != nil {
		var shard string
		if session.UserInfo != nil {
			shard = session.UserInfo.Shard
		}
		if err := h.keystore.Close(req.Context(), shard, session.Username); err != nil {
			log.Printf("failed to wipe keystore for user %s: %v", session.Username, err)
366
		}
ale's avatar
ale committed
367 368
	}

369 370
	w.Header().Set("Content-Security-Policy", logoutContentSecurityPolicy)

371 372 373 374 375 376 377
	body, err := h.renderer.Render(req, "logout.html", data)
	if err != nil {
		log.Printf("template error in logout(): %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Write(body) // nolint
ale's avatar
ale committed
378 379 380 381 382 383 384 385 386
}

func (h *Server) handleExchange(w http.ResponseWriter, req *http.Request) {
	curToken := req.FormValue("cur_tkt")
	curService := req.FormValue("cur_svc")
	curNonce := req.FormValue("cur_nonce")
	newService := req.FormValue("new_svc")
	newNonce := req.FormValue("new_nonce")

387
	token, err := h.loginService.Exchange(curToken, curService, curNonce, newService, newNonce)
ale's avatar
ale committed
388 389 390 391 392 393 394
	switch {
	case err == ErrUnauthorized:
		log.Printf("unauthorized exchange request (%s -> %s)", curService, newService)
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	case err != nil:
		log.Printf("exchange error (%s -> %s): %v", curService, newService, err)
ale's avatar
ale committed
395 396 397 398 399
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	w.Header().Set("Content-Type", "text/plain")
400
	io.WriteString(w, token) // nolint
ale's avatar
ale committed
401 402
}

403 404 405 406
func (h *Server) urlFor(path string) string {
	return h.urlPrefix + path
}

ale's avatar
ale committed
407 408
// Handler returns the http.Handler for the SSO server application.
func (h *Server) Handler() http.Handler {
409 410
	// The root HTTP handler. This must be a gorilla/mux.Router since
	// sessions depend on it.
411 412 413 414 415
	//
	// If a URL prefix is set, we can't just add a StripPrefix in
	// front of everything, as the handlers need access to the
	// actual full request URL, so we just inject the prefix
	// everywhere.
416
	root := mux.NewRouter()
ale's avatar
ale committed
417

418 419 420 421 422 423 424 425
	// If we have customized content, serve it from well-known URLs.
	if h.siteLogo != nil {
		root.Handle(h.urlFor("/img/site_logo"), h.siteLogo)
	}
	if h.siteFavicon != nil {
		root.Handle(h.urlFor("/favicon.ico"), h.siteFavicon)
	}

426
	// Serve static content to anyone.
427 428
	staticPath := h.urlFor("/static/")
	root.PathPrefix(staticPath).Handler(http.StripPrefix(staticPath, http.FileServer(&assetfs.AssetFS{
ale's avatar
ale committed
429 430 431 432 433
		Asset:     Asset,
		AssetDir:  AssetDir,
		AssetInfo: AssetInfo,
		Prefix:    "static",
	})))
ale's avatar
ale committed
434

435 436 437
	// Build the main IDP application router, with optional CSRF
	// protection.
	m := http.NewServeMux()
438
	m.Handle(h.urlFor("/login"), h.loginHandler)
439
	m.Handle(h.urlFor("/logout"), h.withAuth(h.handleLogout, h.alreadyLoggedOut))
440 441 442 443 444 445 446 447
	idph := http.Handler(m)
	if h.csrfSecret != nil {
		idph = csrf.Protect(h.csrfSecret)(idph)
	}

	// Add the SSO provider endpoints (root path and /exchange),
	// which do not need CSRF. We use a HandlerFunc to bypass the
	// '/' dispatch semantics of the standard http.ServeMux.
448
	ssoh := h.withAuth(h.handleHomepage, h.redirectToLogin)
449 450
	userh := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
451
		case r.Method == "GET" && r.URL.Path == h.urlFor("/"):
452
			ssoh.ServeHTTP(w, r)
453
		case r.URL.Path == h.urlFor("/exchange"):
454 455 456 457 458 459
			h.handleExchange(w, r)
		default:
			idph.ServeHTTP(w, r)
		}
	})

ale's avatar
ale committed
460 461 462 463 464 465 466
	// Add CORS headers around user-facing routes.
	c := cors.New(cors.Options{
		AllowedOrigins:   h.allowedOrigins,
		AllowCredentials: true,
		MaxAge:           86400,
	})

467
	// User-facing routes require cache-busting and CSP headers.
ale's avatar
ale committed
468
	root.PathPrefix(h.urlFor("/")).Handler(withDynamicHeaders(c.Handler(userh)))
ale's avatar
ale committed
469

470
	return root
ale's avatar
ale committed
471 472 473 474 475
}

// A relatively strict CSP.
const contentSecurityPolicy = "default-src 'none'; img-src 'self' data:; script-src 'self'; style-src 'self'; connect-src 'self';"

476 477
// Slightly looser CSP for the logout page: it needs to load remote
// images.
478
const logoutContentSecurityPolicy = "default-src 'none'; img-src *; script-src 'self'; style-src 'self'; connect-src *;"
479

ale's avatar
ale committed
480 481 482 483 484 485 486 487
func withDynamicHeaders(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Pragma", "no-cache")
		w.Header().Set("Cache-Control", "no-store")
		w.Header().Set("Expires", "-1")
		w.Header().Set("X-Frame-Options", "NONE")
		w.Header().Set("X-XSS-Protection", "1; mode=block")
		w.Header().Set("X-Content-Type-Options", "nosniff")
488 489 490
		if w.Header().Get("Content-Security-Policy") == "" {
			w.Header().Set("Content-Security-Policy", contentSecurityPolicy)
		}
ale's avatar
ale committed
491 492 493
		h.ServeHTTP(w, r)
	})
}
ale's avatar
ale committed
494

ale's avatar
ale committed
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
// Parse the templates that are embedded with the binary (in bindata.go).
func parseEmbeddedTemplates() *template.Template {
	root := template.New("").Funcs(template.FuncMap{
		"json": toJSON,
	})
	files, err := AssetDir("templates")
	if err != nil {
		log.Fatalf("no asset dir for templates: %v", err)
	}
	for _, f := range files {
		b, err := Asset("templates/" + f)
		if err != nil {
			log.Fatalf("could not read embedded template %s: %v", f, err)
		}
		if _, err := root.New(f).Parse(string(b)); err != nil {
			log.Fatalf("error parsing template %s: %v", f, err)
		}
	}
	return root
}
515 516 517 518 519 520 521 522 523 524 525 526 527 528

type renderer struct {
	tpl *template.Template

	urlPrefix          string
	siteName           string
	siteLogo           string
	siteFavicon        string
	accountRecoveryURL string
}

func newRenderer(config *Config) *renderer {
	return &renderer{
		tpl:                parseEmbeddedTemplates(),
529
		urlPrefix:          strings.TrimRight(config.URLPrefix, "/"),
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 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
		accountRecoveryURL: config.AccountRecoveryURL,
		siteName:           config.SiteName,
		siteLogo:           config.SiteLogo,
		siteFavicon:        config.SiteFavicon,
	}
}

func (r *renderer) Render(req *http.Request, templateName string, data map[string]interface{}) ([]byte, error) {
	data["CSRFField"] = csrf.TemplateField(req)
	data["URLPrefix"] = r.urlPrefix
	data["AccountRecoveryURL"] = r.accountRecoveryURL
	data["SiteName"] = r.siteName
	data["SiteLogo"] = r.siteLogo
	data["SiteFavicon"] = r.siteFavicon

	var buf bytes.Buffer
	if err := r.tpl.ExecuteTemplate(&buf, templateName, data); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

type staticContent struct {
	modtime time.Time
	name    string
	data    []byte
}

func loadStaticContent(path string) (*staticContent, error) {
	stat, err := os.Stat(path)
	if err != nil {
		return nil, err
	}
	data, err := ioutil.ReadFile(path) // #nosec
	if err != nil {
		return nil, err
	}
	return &staticContent{
		name:    path,
		modtime: stat.ModTime(),
		data:    data,
	}, nil
}

func (c *staticContent) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	http.ServeContent(w, req, c.name, c.modtime, bytes.NewReader(c.data))
}