Jelajahi Sumber

Enhanced security and prevent XSS

Toby Chui 9 jam lalu
induk
melakukan
117a1b1d37

+ 6 - 3
src/mod/auth/accountSwitch.go

@@ -55,8 +55,10 @@ func NewSwitchableAccountPoolManager(sysdb *database.Database, parent *AuthAgent
 	sysdb.NewTable("auth_acswitch")
 
 	//Create new session store
+	store := sessions.NewCookieStore(key)
+	store.Options.HttpOnly = true //never readable from page scripts
 	thisManager := SwitchableAccountPoolManager{
-		SessionStore: sessions.NewCookieStore(key),
+		SessionStore: store,
 		SessionName:  "ao_acc",
 		Database:     sysdb,
 		ExpireTime:   604800,
@@ -261,8 +263,9 @@ func (m *SwitchableAccountPoolManager) HandleAccountSwitch(w http.ResponseWriter
 
 		session.Values["poolid"] = poolid
 		session.Options = &sessions.Options{
-			MaxAge: 3600 * 24 * 30, //One month
-			Path:   "/",
+			MaxAge:   3600 * 24 * 30, //One month
+			Path:     "/",
+			HttpOnly: true,
 		}
 		session.Save(r, w)
 	}

+ 11 - 4
src/mod/auth/auth.go

@@ -102,6 +102,9 @@ type AuthEndpoints struct {
 // Constructor
 func NewAuthenticationAgent(sessionName string, key []byte, sysdb *db.Database, allowReg bool, loginRedirectionHandler func(http.ResponseWriter, *http.Request)) *AuthAgent {
 	store := sessions.NewCookieStore(key)
+	//The session cookie is never readable from page scripts, so a script
+	//that gets onto this site cannot carry the session away
+	store.Options.HttpOnly = true
 	err := sysdb.NewTable("auth")
 	if err != nil {
 		logger.PrintAndLog("Auth", "Failed to create auth database. Terminating.", nil)
@@ -341,12 +344,14 @@ func (a *AuthAgent) LoginUserByRequest(w http.ResponseWriter, r *http.Request, u
 			MaxAge:   3600 * 24 * 7, //One week
 			Path:     "/",
 			SameSite: CookieSetSameSitePolicy,
+			HttpOnly: true,
 		}
 	} else {
 		session.Options = &sessions.Options{
 			MaxAge:   3600 * 1, //One hour
 			Path:     "/",
 			SameSite: CookieSetSameSitePolicy,
+			HttpOnly: true,
 		}
 	}
 	session.Save(r, w)
@@ -621,13 +626,15 @@ func (a *AuthAgent) UpdateSessionExpireTime(w http.ResponseWriter, r *http.Reque
 		//Extend the session expire time
 		if rememberme {
 			session.Options = &sessions.Options{
-				MaxAge: 3600 * 24 * 7, //One week
-				Path:   "/",
+				MaxAge:   3600 * 24 * 7, //One week
+				Path:     "/",
+				HttpOnly: true,
 			}
 		} else {
 			session.Options = &sessions.Options{
-				MaxAge: 3600 * 1, //One hour
-				Path:   "/",
+				MaxAge:   3600 * 1, //One hour
+				Path:     "/",
+				HttpOnly: true,
 			}
 		}
 		session.Save(r, w)

+ 3 - 2
src/mod/auth/autologin.go

@@ -159,8 +159,9 @@ func (a *AuthAgent) HandleAutologinTokenLogin(w http.ResponseWriter, r *http.Req
 
 	//Check if remember me is clicked. If yes, set the maxage to 1 week.
 	session.Options = &sessions.Options{
-		MaxAge: 3600 * 1, //1 hour
-		Path:   "/",
+		MaxAge:   3600 * 1, //1 hour
+		Path:     "/",
+		HttpOnly: true,
 	}
 
 	session.Save(r, w)

+ 83 - 0
src/mod/auth/httponly_test.go

@@ -0,0 +1,83 @@
+package auth
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"path/filepath"
+	"testing"
+
+	"imuslab.com/arozos/mod/database"
+)
+
+// The session cookie must never be readable from page scripts: a script that
+// gets onto the site (a user file shown inline, a personal site page) could
+// otherwise carry the session away.
+
+func cookieNamed(cookies []*http.Cookie, name string) *http.Cookie {
+	for _, c := range cookies {
+		if c.Name == name {
+			return c
+		}
+	}
+	return nil
+}
+
+func TestSessionCookieIsHttpOnly(t *testing.T) {
+	tests := []struct {
+		name       string
+		rememberMe bool
+	}{
+		{"one hour session", false},
+		{"remember me", true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			a := newTestAuthAgent(t, nil)
+			rec := httptest.NewRecorder()
+			a.LoginUserByRequest(rec, httptest.NewRequest(http.MethodPost, "/system/auth/login", nil), "alice", tt.rememberMe)
+			c := cookieNamed(rec.Result().Cookies(), "ao_auth")
+			if c == nil {
+				t.Fatal("login set no ao_auth cookie")
+			}
+			if !c.HttpOnly {
+				t.Error("the ao_auth cookie set at login is readable from scripts")
+			}
+		})
+	}
+}
+
+func TestSessionRefreshKeepsHttpOnly(t *testing.T) {
+	for _, rememberMe := range []bool{false, true} {
+		a := newTestAuthAgent(t, nil)
+		login := httptest.NewRecorder()
+		a.LoginUserByRequest(login, httptest.NewRequest(http.MethodPost, "/system/auth/login", nil), "alice", rememberMe)
+
+		req := httptest.NewRequest(http.MethodGet, "/desktop.html", nil)
+		for _, c := range login.Result().Cookies() {
+			req.AddCookie(c)
+		}
+		rec := httptest.NewRecorder()
+		if !a.UpdateSessionExpireTime(rec, req) {
+			t.Fatalf("remember me %v: the signed in session was not refreshed", rememberMe)
+		}
+		c := cookieNamed(rec.Result().Cookies(), "ao_auth")
+		if c == nil {
+			t.Fatalf("remember me %v: the refresh set no ao_auth cookie", rememberMe)
+		}
+		if !c.HttpOnly {
+			t.Errorf("remember me %v: the refreshed ao_auth cookie is readable from scripts", rememberMe)
+		}
+	}
+}
+
+func TestAccountSwitchStoreIsHttpOnly(t *testing.T) {
+	sysdb, err := database.NewDatabase(filepath.Join(t.TempDir(), "acswitch.db"), false)
+	if err != nil {
+		t.Fatalf("NewDatabase returned error: %v", err)
+	}
+	t.Cleanup(sysdb.Close)
+	m := NewSwitchableAccountPoolManager(sysdb, newTestAuthAgent(t, nil), []byte("0123456789abcdef0123456789abcdef"))
+	if !m.SessionStore.Options.HttpOnly {
+		t.Error("the ao_acc cookie store lets scripts read its cookie")
+	}
+}

+ 32 - 0
src/mod/auth/oauth2/cookie_test.go

@@ -0,0 +1,32 @@
+package oauth2
+
+import (
+	"net/http/httptest"
+	"testing"
+	"time"
+)
+
+// The login state cookie of the OAuth sign in is never readable from scripts
+func TestAddCookieIsHttpOnly(t *testing.T) {
+	tests := []struct {
+		name  string
+		value string
+		ttl   time.Duration
+	}{
+		{"login state", "3f6c2a1e-uuid", 30 * time.Minute},
+		{"cleared", "-invalid-", -1},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			rec := httptest.NewRecorder()
+			(&OauthHandler{}).addCookie(rec, "uuid_login", tt.value, tt.ttl)
+			cookies := rec.Result().Cookies()
+			if len(cookies) != 1 {
+				t.Fatalf("got %d cookies, want 1", len(cookies))
+			}
+			if !cookies[0].HttpOnly {
+				t.Error("uuid_login is readable from scripts")
+			}
+		})
+	}
+}

+ 4 - 3
src/mod/auth/oauth2/oauth2.go

@@ -378,9 +378,10 @@ func (oh *OauthHandler) WriteConfig(w http.ResponseWriter, r *http.Request) {
 
 func (oh *OauthHandler) addCookie(w http.ResponseWriter, name, value string, ttl time.Duration) {
 	http.SetCookie(w, &http.Cookie{
-		Name:    name,
-		Value:   value,
-		Expires: time.Now().Add(ttl),
+		Name:     name,
+		Value:    value,
+		Expires:  time.Now().Add(ttl),
+		HttpOnly: true, //part of signing in: never readable from page scripts
 	})
 }
 

+ 3 - 0
src/mod/media/mediaserver/mediaserver.go

@@ -275,6 +275,9 @@ func (s *Instance) ServerMedia(w http.ResponseWriter, r *http.Request) {
 		}
 
 	} else {
+		//Shown inline on this site: a file that could be a page (HTML, SVG)
+		//is sandboxed, so it cannot act as the user who opens it
+		utils.SetUserContentHeaders(w, realFilepath)
 		if nocacheMode {
 			// Add no-cache headers to prevent browser caching, useful for development and testing
 			w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate")

+ 5 - 1
src/mod/network/webdav/webdav.go

@@ -15,6 +15,8 @@ import (
 	"path"
 	"strings"
 	"time"
+
+	"imuslab.com/arozos/mod/utils"
 )
 
 type Handler struct {
@@ -228,7 +230,9 @@ func (h *Handler) handleGetHeadPost(w http.ResponseWriter, r *http.Request) (sta
 		return http.StatusInternalServerError, err
 	}
 	w.Header().Set("ETag", etag)
-	// Let ServeContent determine the Content-Type header.
+	// A browser opening a file here shows it on this site: a file that could
+	// be a page (HTML, SVG) is sandboxed. ServeContent sets the type otherwise.
+	utils.SetUserContentHeaders(w, reqPath)
 	http.ServeContent(w, r, reqPath, fi.ModTime(), f)
 	return 0, nil
 }

+ 44 - 0
src/mod/share/preview_security_test.go

@@ -0,0 +1,44 @@
+package share
+
+import (
+	"mime"
+	"net/http/httptest"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+// A share link is opened on this site by anyone, often while signed in: a
+// shared file that could be a page must come back sandboxed
+func TestSetPreviewContentType(t *testing.T) {
+	tests := []struct {
+		file        string
+		wantSandbox bool
+		wantType    string
+	}{
+		{"index.html", true, "text/html"},
+		{"logo.svg", true, "image/svg+xml"},
+		{"README", true, ""},
+		{"photo.png", false, "image/png"},
+		{"report.pdf", false, "application/pdf"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.file, func(t *testing.T) {
+			rec := httptest.NewRecorder()
+			setPreviewContentType(rec, mime.TypeByExtension(filepath.Ext(tt.file)), "/data/"+tt.file)
+			csp := rec.Header().Get("Content-Security-Policy")
+			if tt.wantSandbox != strings.HasPrefix(csp, "sandbox") {
+				t.Errorf("Content-Security-Policy = %q, want sandbox %v", csp, tt.wantSandbox)
+			}
+			if strings.Contains(csp, "allow-same-origin") {
+				t.Errorf("the sandbox keeps the site's origin: %q", csp)
+			}
+			if tt.wantType != "" && !strings.HasPrefix(rec.Header().Get("Content-Type"), tt.wantType) {
+				t.Errorf("Content-Type = %q, want %s", rec.Header().Get("Content-Type"), tt.wantType)
+			}
+			if tt.wantType == "" && rec.Header().Get("Content-Type") != "" {
+				t.Errorf("Content-Type = %q set for a file of unknown type", rec.Header().Get("Content-Type"))
+			}
+		})
+	}
+}

+ 12 - 2
src/mod/share/share.go

@@ -1006,6 +1006,16 @@ func setShareRevalidation(w http.ResponseWriter, targetFsh *filesystem.FileSyste
 	utils.SetRevalidationHeaders(w, info)
 }
 
+// setPreviewContentType sets the type of a shared file shown inline. Anyone
+// with the link opens it on this site, often while signed in, so a file that
+// could be a page (HTML, SVG) is sandboxed (utils.SetUserContentHeaders).
+func setPreviewContentType(w http.ResponseWriter, contentType string, path string) {
+	if contentType != "" {
+		w.Header().Set("Content-Type", contentType)
+	}
+	utils.SetUserContentHeaders(w, path)
+}
+
 // servePreview streams a shared file inline for in-browser viewing
 func (s *Manager) servePreview(w http.ResponseWriter, r *http.Request, targetFsh *filesystem.FileSystemHandler, fileRuntimeAbsPath string) {
 	targetFshAbs := targetFsh.FileSystemAbstraction
@@ -1031,7 +1041,7 @@ func (s *Manager) servePreview(w http.ResponseWriter, r *http.Request, targetFsh
 		w.Header().Set("Content-Type", "image/jpeg")
 		w.Write(jpegData)
 	} else if targetFsh.RequireBuffer {
-		w.Header().Set("Content-Type", contentType)
+		setPreviewContentType(w, contentType, fileRuntimeAbsPath)
 		f, err := targetFshAbs.ReadStream(fileRuntimeAbsPath)
 		if err != nil {
 			w.WriteHeader(http.StatusInternalServerError)
@@ -1041,7 +1051,7 @@ func (s *Manager) servePreview(w http.ResponseWriter, r *http.Request, targetFsh
 		defer f.Close()
 		io.Copy(w, f)
 	} else {
-		w.Header().Set("Content-Type", contentType)
+		setPreviewContentType(w, contentType, fileRuntimeAbsPath)
 		f, err := targetFshAbs.Open(fileRuntimeAbsPath)
 		if err != nil {
 			w.WriteHeader(http.StatusInternalServerError)

+ 66 - 0
src/mod/utils/usercontent.go

@@ -0,0 +1,66 @@
+package utils
+
+import (
+	"mime"
+	"net/http"
+	"path/filepath"
+	"strings"
+)
+
+/*
+	User files shown inline
+
+	Files users upload are served on the ArozOS origin itself (/media, share
+	preview links, WebDAV). A file a browser can run as a page (HTML, SVG,
+	XML) would run with the session of whoever opens it, so a user could
+	share one and act as everyone who looks at it. Such files are therefore
+	sent with a sandbox Content-Security-Policy: the browser gives the page
+	an origin of its own, so its scripts still run (previews keep working)
+	but cannot read this site's cookies, storage, API answers or the desktop
+	around it. Pictures, video, audio, PDF and text are left as they are.
+*/
+
+// UserContentSandbox is the Content-Security-Policy of a user file that a
+// browser could open as a page. It has no allow-same-origin on purpose.
+const UserContentSandbox = "sandbox allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads"
+
+// IsActiveUserContent reports whether a browser may run scripts in a file
+// of this name when it is opened as a page: HTML, XHTML, SVG and XML of any
+// kind (XSLT can turn it into HTML), and any file whose type the extension
+// does not tell, which the server or the browser would sniff.
+func IsActiveUserContent(filename string) bool {
+	ext := strings.ToLower(filepath.Ext(filename))
+	if ext == "" {
+		return true
+	}
+	ctype := mime.TypeByExtension(ext)
+	if ctype == "" {
+		return true
+	}
+	mediaType, _, err := mime.ParseMediaType(ctype)
+	if err != nil {
+		return true
+	}
+	switch mediaType {
+	case "text/html", "application/xhtml+xml", "image/svg+xml", "text/xml", "application/xml",
+		"text/xsl", "application/xslt+xml", "message/rfc822", "multipart/related", "application/octet-stream":
+		return true
+	}
+	return strings.HasSuffix(mediaType, "+xml")
+}
+
+// SetUserContentHeaders prepares the answer that shows a user file inline.
+// Call it before http.ServeFile, http.ServeContent or copying the file out.
+// A file that could be a page gets the sandbox policy and nosniff; every
+// other file gets the Content-Type of its extension set here, so a server
+// side guess from its bytes (a .png that holds HTML) never decides it.
+func SetUserContentHeaders(w http.ResponseWriter, filename string) {
+	if IsActiveUserContent(filename) {
+		w.Header().Set("Content-Security-Policy", UserContentSandbox)
+		w.Header().Set("X-Content-Type-Options", "nosniff")
+		return
+	}
+	if w.Header().Get("Content-Type") == "" {
+		w.Header().Set("Content-Type", mime.TypeByExtension(strings.ToLower(filepath.Ext(filename))))
+	}
+}

+ 105 - 0
src/mod/utils/usercontent_test.go

@@ -0,0 +1,105 @@
+package utils
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+func TestIsActiveUserContent(t *testing.T) {
+	tests := []struct {
+		name string
+		want bool
+	}{
+		{"evil.html", true},
+		{"EVIL.HTM", true},
+		{"page.xhtml", true},
+		{"drawing.svg", true},
+		{"feed.xml", true},
+		{"style.xsl", true},
+		{"no_extension", true},
+		{"data.unknownext123", true},
+		{"photo.png", false},
+		{"photo.JPG", false},
+		{"clip.mp4", false},
+		{"song.mp3", false},
+		{"report.pdf", false},
+		{"notes.txt", false},
+		{"style.css", false},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := IsActiveUserContent(tt.name); got != tt.want {
+				t.Errorf("IsActiveUserContent(%q) = %v, want %v", tt.name, got, tt.want)
+			}
+		})
+	}
+}
+
+// What a browser gets for a user file served the way /media serves it
+func serveUserFile(t *testing.T, name string, content string) *http.Response {
+	t.Helper()
+	dir := t.TempDir()
+	path := filepath.Join(dir, name)
+	if err := os.WriteFile(path, []byte(content), 0644); err != nil {
+		t.Fatalf("write: %v", err)
+	}
+	rec := httptest.NewRecorder()
+	req := httptest.NewRequest(http.MethodGet, "/media?file=user:/"+name, nil)
+	SetUserContentHeaders(rec, name)
+	http.ServeFile(rec, req, path)
+	return rec.Result()
+}
+
+func TestSetUserContentHeaders(t *testing.T) {
+	script := "<!DOCTYPE html><html><script>fetch('/system/users/list')</script></html>"
+	tests := []struct {
+		name        string
+		file        string
+		content     string
+		wantSandbox bool
+		wantType    string // prefix of the Content-Type, "" to skip
+	}{
+		{"html page", "evil.html", script, true, "text/html"},
+		{"svg with script", "evil.svg", `<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/>`, true, "image/svg+xml"},
+		{"html without extension", "evil", script, true, ""},
+		{"html named as an unknown type", "evil.aopart", script, true, ""},
+		{"html named as a png", "evil.png", script, false, "image/png"},
+		{"html named as text", "evil.txt", script, false, "text/plain"},
+		{"real picture", "photo.jpg", "\xff\xd8\xff\xe0", false, "image/jpeg"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			res := serveUserFile(t, tt.file, tt.content)
+			csp := res.Header.Get("Content-Security-Policy")
+			if tt.wantSandbox {
+				if !strings.HasPrefix(csp, "sandbox") || strings.Contains(csp, "allow-same-origin") {
+					t.Errorf("Content-Security-Policy = %q, want a sandbox without allow-same-origin", csp)
+				}
+				if res.Header.Get("X-Content-Type-Options") != "nosniff" {
+					t.Error("nosniff is missing")
+				}
+			} else if csp != "" {
+				t.Errorf("Content-Security-Policy = %q, want none", csp)
+			}
+			if tt.wantType != "" && !strings.HasPrefix(res.Header.Get("Content-Type"), tt.wantType) {
+				t.Errorf("Content-Type = %q, want %s", res.Header.Get("Content-Type"), tt.wantType)
+			}
+			if strings.HasPrefix(res.Header.Get("Content-Type"), "text/html") && !tt.wantSandbox {
+				t.Error("an HTML page went out without the sandbox")
+			}
+		})
+	}
+}
+
+func TestSetUserContentHeadersKeepsAGivenType(t *testing.T) {
+	rec := httptest.NewRecorder()
+	rec.Header().Set("Content-Type", "image/jpeg")
+	SetUserContentHeaders(rec, "photo.arw")
+	if got := rec.Header().Get("Content-Type"); got != "image/jpeg" {
+		t.Errorf("Content-Type = %q, want the one already set", got)
+	}
+}