Procházet zdrojové kódy

Fixed #314

Fixed 314 by properly implementing a session revoke flow
Toby Chui před 1 týdnem
rodič
revize
ec85935bbd

+ 24 - 2
src/mod/auth/auth.go

@@ -77,6 +77,9 @@ type AuthAgent struct {
 
 	//Account creation policy for /system/auth/register, wired in by main
 	RegisterAuthorizer *RegisterAuthorizer
+
+	//Session ids that were logged out, see revoke.go
+	revokedSessions *sessionRevoker
 }
 
 // RegisterAuthorizer holds the permission checks HandleRegister needs. The auth
@@ -146,6 +149,9 @@ func NewAuthenticationAgent(sessionName string, key []byte, sysdb *db.Database,
 
 		//Switchable Account Pool Manager
 		Logger: newLogger,
+
+		//Logged out sessions
+		revokedSessions: newSessionRevoker(sysdb),
 	}
 
 	poolManager := NewSwitchableAccountPoolManager(sysdb, &newAuthAgent, key)
@@ -159,6 +165,7 @@ func NewAuthenticationAgent(sessionName string, key []byte, sysdb *db.Database,
 				return
 			case <-ticker.C:
 				listeningAuthAgent.ClearTokenStore()
+				listeningAuthAgent.revokedSessions.Prune()
 			}
 		}
 	}(&newAuthAgent)
@@ -320,6 +327,7 @@ func (a *AuthAgent) LoginUserByRequest(w http.ResponseWriter, r *http.Request, u
 	session.Values["authenticated"] = true
 	session.Values["username"] = username
 	session.Values["rememberMe"] = rememberme
+	startSession(session)
 
 	CookieSetSameSitePolicy := http.SameSiteNoneMode
 	if r.TLS == nil {
@@ -374,8 +382,13 @@ func (a *AuthAgent) Logout(w http.ResponseWriter, r *http.Request) error {
 	if err != nil {
 		return err
 	}
+	//Revoke the session id, so copies of the signed-in cookie that are still
+	//on their way to the browser (or kept anywhere else) stop working
+	a.revokedSessions.Revoke(sessionIDOf(session))
+
 	session.Values["authenticated"] = false
 	session.Values["username"] = nil
+	delete(session.Values, sessionIDKey)
 	session.Save(r, w)
 
 	return nil
@@ -489,6 +502,11 @@ func (a *AuthAgent) CheckAuth(r *http.Request) bool {
 	if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
 		return false
 	}
+	// A logged out session stays logged out, even when a stale copy of its
+	// cookie reaches the browser after the logout
+	if a.revokedSessions.IsRevoked(sessionIDOf(session)) {
+		return false
+	}
 	return true
 }
 
@@ -593,9 +611,13 @@ func (a *AuthAgent) UserExists(username string) bool {
 // Update the session expire time given the request header.
 func (a *AuthAgent) UpdateSessionExpireTime(w http.ResponseWriter, r *http.Request) bool {
 	session, _ := a.SessionStore.Get(r, a.SessionName)
-	if session.Values["authenticated"].(bool) {
+	if a.CheckAuth(r) {
 		//User authenticated. Extend its expire time
-		rememberme := session.Values["rememberMe"].(bool)
+		rememberme, _ := session.Values["rememberMe"].(bool)
+		if sessionIDOf(session) == "" {
+			//Signed in before session ids existed: give it one so it can be logged out
+			startSession(session)
+		}
 		//Extend the session expire time
 		if rememberme {
 			session.Options = &sessions.Options{

+ 1 - 0
src/mod/auth/autologin.go

@@ -153,6 +153,7 @@ func (a *AuthAgent) HandleAutologinTokenLogin(w http.ResponseWriter, r *http.Req
 	session.Values["authenticated"] = true
 	session.Values["username"] = username
 	session.Values["rememberMe"] = false
+	startSession(session)
 
 	logger.PrintAndLog("Auth", username+" logged in via auto-login token", nil)
 

+ 150 - 0
src/mod/auth/revoke.go

@@ -0,0 +1,150 @@
+package auth
+
+import (
+	"crypto/rand"
+	"encoding/hex"
+	"encoding/json"
+	"sync"
+	"time"
+
+	"github.com/gorilla/sessions"
+	db "imuslab.com/arozos/mod/database"
+	"imuslab.com/arozos/mod/info/logger"
+)
+
+/*
+	Session revocation
+
+	The login session lives in a signed cookie (gorilla CookieStore), so the
+	server keeps no record of it and logging out only overwrites the cookie in
+	the browser. Every signed-in request also writes a refreshed copy of the
+	cookie (UpdateSessionExpireTime). When the desktop logs out while other
+	requests are still in flight, their responses can reach the browser after
+	the logout response and put a signed-in cookie back: the user lands on the
+	desktop again instead of the login page (issue #314).
+
+	Each login therefore carries a random session id. Logout revokes that id,
+	and CheckAuth refuses every cookie holding a revoked id, however late it
+	arrives. Revoked ids are kept as long as a cookie signed before the logout
+	can still be decoded, and stored in the system database so a restart does
+	not bring them back.
+*/
+
+const (
+	sessionIDKey        = "sid"          //Session value holding the session id
+	revokedSessionTable = "auth_revoked" //System database table of revoked session ids
+	sessionRevokeKeep   = 86400 * 30     //Seconds a revoked id is remembered (securecookie default max age)
+	sessionIDBytes      = 16             //Random bytes in a session id
+)
+
+type sessionRevoker struct {
+	mutex    sync.RWMutex
+	revoked  map[string]int64 //Session id to the unix time it can be forgotten
+	database *db.Database
+}
+
+// newSessionRevoker loads the revoked session ids still in effect from the
+// system database.
+func newSessionRevoker(sysdb *db.Database) *sessionRevoker {
+	r := &sessionRevoker{
+		revoked:  map[string]int64{},
+		database: sysdb,
+	}
+	if sysdb == nil {
+		return r
+	}
+	if err := sysdb.NewTable(revokedSessionTable); err != nil {
+		logger.PrintAndLog("Auth", "Unable to create the revoked session table", err)
+		return r
+	}
+	entries, err := sysdb.ListTable(revokedSessionTable)
+	if err != nil {
+		logger.PrintAndLog("Auth", "Unable to load revoked sessions", err)
+		return r
+	}
+	now := time.Now().Unix()
+	for _, keypairs := range entries {
+		var expire int64
+		if json.Unmarshal(keypairs[1], &expire) != nil || expire <= now {
+			sysdb.Delete(revokedSessionTable, string(keypairs[0]))
+			continue
+		}
+		r.revoked[string(keypairs[0])] = expire
+	}
+	return r
+}
+
+// Revoke marks a session id as logged out.
+func (r *sessionRevoker) Revoke(sid string) {
+	if r == nil || sid == "" {
+		return
+	}
+	expire := time.Now().Unix() + sessionRevokeKeep
+	r.mutex.Lock()
+	r.revoked[sid] = expire
+	r.mutex.Unlock()
+	if r.database != nil {
+		if err := r.database.Write(revokedSessionTable, sid, expire); err != nil {
+			logger.PrintAndLog("Auth", "Unable to store a revoked session", err)
+		}
+	}
+}
+
+// IsRevoked tells if a session id was logged out.
+func (r *sessionRevoker) IsRevoked(sid string) bool {
+	if r == nil || sid == "" {
+		return false
+	}
+	r.mutex.RLock()
+	_, ok := r.revoked[sid]
+	r.mutex.RUnlock()
+	return ok
+}
+
+// Prune forgets the revoked ids no cookie can hold any more.
+func (r *sessionRevoker) Prune() {
+	if r == nil {
+		return
+	}
+	now := time.Now().Unix()
+	expired := []string{}
+	r.mutex.Lock()
+	for sid, expire := range r.revoked {
+		if expire <= now {
+			delete(r.revoked, sid)
+			expired = append(expired, sid)
+		}
+	}
+	r.mutex.Unlock()
+	if r.database == nil || len(expired) == 0 {
+		return
+	}
+	ops := make([]db.BatchOp, 0, len(expired))
+	for _, sid := range expired {
+		ops = append(ops, db.BatchOp{Table: revokedSessionTable, Key: sid, Delete: true})
+	}
+	if err := r.database.WriteBatch(ops); err != nil {
+		logger.PrintAndLog("Auth", "Unable to prune revoked sessions", err)
+	}
+}
+
+// newSessionID returns a random session id.
+func newSessionID() string {
+	buf := make([]byte, sessionIDBytes)
+	if _, err := rand.Read(buf); err != nil {
+		//crypto/rand does not fail on supported platforms
+		panic(err)
+	}
+	return hex.EncodeToString(buf)
+}
+
+// sessionIDOf returns the session id held by a session, empty when it has none.
+func sessionIDOf(session *sessions.Session) string {
+	sid, _ := session.Values[sessionIDKey].(string)
+	return sid
+}
+
+// startSession gives a session that is being signed in a new session id.
+func startSession(session *sessions.Session) {
+	session.Values[sessionIDKey] = newSessionID()
+}

+ 254 - 0
src/mod/auth/revoke_test.go

@@ -0,0 +1,254 @@
+package auth
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"path/filepath"
+	"testing"
+	"time"
+
+	"github.com/gorilla/sessions"
+	db "imuslab.com/arozos/mod/database"
+)
+
+const testSessionName = "ao_auth_test"
+
+// newSessionAgent builds an agent with a cookie store and a revoker backed by
+// a temporary database, enough to sign in, refresh and log out sessions.
+func newSessionAgent(t *testing.T, sysdb *db.Database) *AuthAgent {
+	t.Helper()
+	return &AuthAgent{
+		SessionName:     testSessionName,
+		SessionStore:    sessions.NewCookieStore([]byte("0123456789abcdef0123456789abcdef")),
+		Database:        sysdb,
+		revokedSessions: newSessionRevoker(sysdb),
+	}
+}
+
+func newTestDB(t *testing.T) *db.Database {
+	t.Helper()
+	sysdb, err := db.NewDatabase(filepath.Join(t.TempDir(), "ao.db"), false)
+	if err != nil {
+		t.Fatalf("NewDatabase: %v", err)
+	}
+	t.Cleanup(sysdb.Close)
+	return sysdb
+}
+
+// requestWith returns a request carrying the given session cookie (none when nil).
+func requestWith(cookie *http.Cookie) *http.Request {
+	r := httptest.NewRequest(http.MethodGet, "http://192.168.1.2:8080/desktop.html", nil)
+	if cookie != nil {
+		r.AddCookie(cookie)
+	}
+	return r
+}
+
+// sessionCookie returns the last session cookie a response set, like a browser keeps it.
+func sessionCookie(t *testing.T, rec *httptest.ResponseRecorder) *http.Cookie {
+	t.Helper()
+	var found *http.Cookie
+	for _, c := range rec.Result().Cookies() {
+		if c.Name == testSessionName {
+			found = c
+		}
+	}
+	if found == nil {
+		t.Fatalf("response set no session cookie")
+	}
+	return found
+}
+
+func login(t *testing.T, a *AuthAgent, username string) *http.Cookie {
+	t.Helper()
+	rec := httptest.NewRecorder()
+	a.LoginUserByRequest(rec, requestWith(nil), username, false)
+	return sessionCookie(t, rec)
+}
+
+// refresh is any signed-in request: the router extends the session on each one.
+func refresh(t *testing.T, a *AuthAgent, cookie *http.Cookie) *http.Cookie {
+	t.Helper()
+	rec := httptest.NewRecorder()
+	if !a.UpdateSessionExpireTime(rec, requestWith(cookie)) {
+		t.Fatalf("UpdateSessionExpireTime refused a signed-in session")
+	}
+	return sessionCookie(t, rec)
+}
+
+func logout(t *testing.T, a *AuthAgent, cookie *http.Cookie) *http.Cookie {
+	t.Helper()
+	rec := httptest.NewRecorder()
+	if err := a.Logout(rec, requestWith(cookie)); err != nil {
+		t.Fatalf("Logout: %v", err)
+	}
+	return sessionCookie(t, rec)
+}
+
+// Issue #314: a request sent just before logout answers with a refreshed
+// signed-in cookie. When that answer reaches the browser after the logout
+// answer, the browser must still be logged out.
+func TestLogoutSurvivesLateRefreshedCookie(t *testing.T) {
+	a := newSessionAgent(t, newTestDB(t))
+	signedIn := login(t, a, "alice")
+	if !a.CheckAuth(requestWith(signedIn)) {
+		t.Fatalf("fresh login is not signed in")
+	}
+
+	inFlight := refresh(t, a, signedIn) //Desktop poll still on its way
+	loggedOut := logout(t, a, signedIn)
+
+	if a.CheckAuth(requestWith(loggedOut)) {
+		t.Errorf("logout cookie is still signed in")
+	}
+	if a.CheckAuth(requestWith(inFlight)) {
+		t.Errorf("cookie refreshed before the logout signs the browser back in")
+	}
+	if a.CheckAuth(requestWith(signedIn)) {
+		t.Errorf("original cookie still works after logout")
+	}
+	rec := httptest.NewRecorder()
+	if a.UpdateSessionExpireTime(rec, requestWith(inFlight)) {
+		t.Errorf("a revoked session was refreshed")
+	}
+}
+
+func TestLoginAfterLogoutStartsNewSession(t *testing.T) {
+	a := newSessionAgent(t, newTestDB(t))
+	first := login(t, a, "alice")
+	logout(t, a, first)
+
+	second := login(t, a, "alice")
+	if !a.CheckAuth(requestWith(second)) {
+		t.Fatalf("signing in again after logout failed")
+	}
+	if !a.CheckAuth(requestWith(refresh(t, a, second))) {
+		t.Errorf("refreshed new session is not signed in")
+	}
+}
+
+func TestLogoutKeepsOtherSessions(t *testing.T) {
+	a := newSessionAgent(t, newTestDB(t))
+	laptop := login(t, a, "alice")
+	phone := login(t, a, "alice")
+	logout(t, a, laptop)
+	if !a.CheckAuth(requestWith(phone)) {
+		t.Errorf("logging out one browser signed out another")
+	}
+}
+
+// Sessions signed in before session ids existed get one on their next
+// request, so they can be logged out like any other.
+func TestLegacySessionGetsIDOnRefresh(t *testing.T) {
+	a := newSessionAgent(t, newTestDB(t))
+	rec := httptest.NewRecorder()
+	r := requestWith(nil)
+	session, _ := a.SessionStore.Get(r, a.SessionName)
+	session.Values["authenticated"] = true
+	session.Values["username"] = "alice"
+	session.Values["rememberMe"] = true
+	session.Save(r, rec)
+	legacy := sessionCookie(t, rec)
+
+	upgraded := refresh(t, a, legacy)
+	inFlight := refresh(t, a, upgraded)
+	logout(t, a, upgraded)
+	if a.CheckAuth(requestWith(inFlight)) {
+		t.Errorf("upgraded legacy session survived logout")
+	}
+}
+
+func TestLogoutWithoutSession(t *testing.T) {
+	a := newSessionAgent(t, newTestDB(t))
+	if a.CheckAuth(requestWith(logout(t, a, nil))) {
+		t.Errorf("logging out an empty session signed it in")
+	}
+}
+
+func TestRevokedSessionsSurviveRestart(t *testing.T) {
+	sysdb := newTestDB(t)
+	a := newSessionAgent(t, sysdb)
+	signedIn := login(t, a, "alice")
+	inFlight := refresh(t, a, signedIn)
+	logout(t, a, signedIn)
+
+	restarted := newSessionAgent(t, sysdb)
+	restarted.SessionStore = a.SessionStore
+	if restarted.CheckAuth(requestWith(inFlight)) {
+		t.Errorf("revoked session works again after a restart")
+	}
+}
+
+func TestRevokerPrune(t *testing.T) {
+	sysdb := newTestDB(t)
+	r := newSessionRevoker(sysdb)
+	r.Revoke("current")
+	r.Revoke("old")
+	r.revoked["old"] = time.Now().Unix() - 1
+
+	r.Prune()
+
+	tests := []struct {
+		sid  string
+		want bool
+	}{
+		{"current", true},
+		{"old", false},
+		{"", false},
+		{"never", false},
+	}
+	for _, tc := range tests {
+		if got := r.IsRevoked(tc.sid); got != tc.want {
+			t.Errorf("IsRevoked(%q) = %v, want %v", tc.sid, got, tc.want)
+		}
+	}
+	if sysdb.KeyExists(revokedSessionTable, "old") {
+		t.Errorf("pruned id is still in the database")
+	}
+	if !newSessionRevoker(sysdb).IsRevoked("current") {
+		t.Errorf("revoked id was not stored")
+	}
+}
+
+func TestRevokerExpiredOnLoad(t *testing.T) {
+	sysdb := newTestDB(t)
+	if err := sysdb.NewTable(revokedSessionTable); err != nil {
+		t.Fatalf("NewTable: %v", err)
+	}
+	sysdb.Write(revokedSessionTable, "stale", time.Now().Unix()-10)
+	sysdb.Write(revokedSessionTable, "live", time.Now().Unix()+100)
+
+	r := newSessionRevoker(sysdb)
+	if r.IsRevoked("stale") {
+		t.Errorf("expired id was loaded")
+	}
+	if !r.IsRevoked("live") {
+		t.Errorf("live id was not loaded")
+	}
+	if sysdb.KeyExists(revokedSessionTable, "stale") {
+		t.Errorf("expired id was left in the database")
+	}
+}
+
+func TestNilRevoker(t *testing.T) {
+	var r *sessionRevoker
+	r.Revoke("x")
+	r.Prune()
+	if r.IsRevoked("x") {
+		t.Errorf("nil revoker reported a revoked id")
+	}
+}
+
+func TestNewSessionIDUnique(t *testing.T) {
+	seen := map[string]bool{}
+	for i := 0; i < 100; i++ {
+		sid := newSessionID()
+		if len(sid) != sessionIDBytes*2 {
+			t.Fatalf("session id %q has length %d", sid, len(sid))
+		}
+		if seen[sid] {
+			t.Fatalf("duplicate session id %q", sid)
+		}
+		seen[sid] = true
+	}
+}