441 lines
14 KiB
Go
441 lines
14 KiB
Go
package fbhttp
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/coreos/go-oidc/v3/oidc"
|
|
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
|
"github.com/filebrowser/filebrowser/v2/settings"
|
|
"github.com/filebrowser/filebrowser/v2/storage"
|
|
"github.com/filebrowser/filebrowser/v2/users"
|
|
"golang.org/x/oauth2"
|
|
)
|
|
|
|
type identityKey struct{}
|
|
type sessionIdentity struct {
|
|
ID uint
|
|
Admin bool
|
|
Name string
|
|
}
|
|
type ssoClaims struct {
|
|
Subject string `json:"sub"`
|
|
Username string `json:"preferred_username"`
|
|
Name string `json:"name"`
|
|
Email string `json:"email"`
|
|
Roles []string `json:"roles"`
|
|
}
|
|
type loginAttempt struct {
|
|
Nonce, Verifier, ReturnTo string
|
|
Expires time.Time
|
|
}
|
|
type ssoSession struct {
|
|
sync.Mutex
|
|
Identity sessionIdentity
|
|
Expires time.Time
|
|
Touched time.Time
|
|
}
|
|
|
|
// SSO owns opaque server-side sessions (8h absolute, 30m idle). Roles are
|
|
// captured at login. Provider tokens are discarded after OIDC verification.
|
|
type SSO struct {
|
|
provider *oidc.Provider
|
|
verifier *oidc.IDTokenVerifier
|
|
oauth oauth2.Config
|
|
origin, base, cookiePath string
|
|
secure bool
|
|
issuer string
|
|
store *storage.Storage
|
|
server *settings.Server
|
|
mu sync.Mutex
|
|
provision sync.Mutex
|
|
userIDs map[string]uint
|
|
attempts map[string]loginAttempt
|
|
sessions map[[32]byte]*ssoSession
|
|
}
|
|
|
|
type SSOConfig struct {
|
|
Issuer string `json:"issuer"`
|
|
ClientID string `json:"clientID"`
|
|
ClientSecret string `json:"clientSecret"`
|
|
PublicURL string `json:"publicURL"`
|
|
}
|
|
|
|
func NewSSO(ctx context.Context, store *storage.Storage, server *settings.Server, config SSOConfig) (*SSO, error) {
|
|
issuer, clientID, secret, publicURL := config.Issuer, config.ClientID, config.ClientSecret, config.PublicURL
|
|
if issuer == "" || clientID == "" || secret == "" || publicURL == "" {
|
|
return nil, errors.New("SSO is required: run filebrowser init first")
|
|
}
|
|
u, err := url.Parse(publicURL)
|
|
if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Scheme != "https" && !(u.Scheme == "http" && (u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1"))) {
|
|
return nil, errors.New("sso.publicURL must be an HTTPS URL (HTTP allowed only on loopback)")
|
|
}
|
|
i, err := url.Parse(issuer)
|
|
if err != nil || i.Host == "" || i.User != nil || (i.Scheme != "https" && !(i.Scheme == "http" && (i.Hostname() == "localhost" || i.Hostname() == "127.0.0.1"))) {
|
|
return nil, errors.New("sso.issuer must use HTTPS (HTTP allowed only on loopback)")
|
|
}
|
|
base := strings.TrimRight(u.Path, "/")
|
|
if base != strings.TrimRight(server.BaseURL, "/") {
|
|
return nil, errors.New("sso.publicURL path must match baseURL")
|
|
}
|
|
client := &http.Client{Timeout: 15 * time.Second}
|
|
ctx = oidc.ClientContext(ctx, client)
|
|
provider, err := oidc.NewProvider(ctx, strings.TrimRight(issuer, "/"))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("SSO discovery: %w", err)
|
|
}
|
|
endpoint := provider.Endpoint()
|
|
endpoint.AuthStyle = oauth2.AuthStyleInHeader
|
|
s := &SSO{provider: provider, verifier: provider.Verifier(&oidc.Config{ClientID: clientID, SupportedSigningAlgs: []string{oidc.RS256}}), origin: u.Scheme + "://" + u.Host, base: base, cookiePath: base + "/", secure: u.Scheme == "https", issuer: strings.TrimRight(issuer, "/"), store: store, server: server, attempts: map[string]loginAttempt{}, sessions: map[[32]byte]*ssoSession{}}
|
|
s.oauth = oauth2.Config{ClientID: clientID, ClientSecret: secret, Endpoint: endpoint, RedirectURL: strings.TrimRight(publicURL, "/") + "/auth/callback", Scopes: []string{oidc.ScopeOpenID, "profile", "email"}}
|
|
// Remove usable local credentials when migrating an existing installation.
|
|
legacy, err := store.Users.Gets(server.Root, false)
|
|
if err != nil && !errors.Is(err, fberrors.ErrNotExist) {
|
|
return nil, err
|
|
}
|
|
for _, u := range legacy {
|
|
if s.userIDs == nil {
|
|
s.userIDs = map[string]uint{}
|
|
}
|
|
if previous, ok := s.userIDs[u.Username]; !ok || u.ID < previous {
|
|
s.userIDs[u.Username] = u.ID
|
|
}
|
|
if u.Password != "!sso-disabled" || !u.LockPassword || u.Perm.Execute || len(u.Commands) > 0 || u.Perm.Admin {
|
|
u.Password = "!sso-disabled"
|
|
u.LockPassword = true
|
|
u.Perm.Admin = false
|
|
u.Perm.Execute = false
|
|
u.Commands = []string{}
|
|
if err = store.Users.Update(u, "Password", "LockPassword", "Perm", "Commands"); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
func randomSecret() string {
|
|
b := make([]byte, 32)
|
|
if _, err := rand.Read(b); err != nil {
|
|
panic(err)
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(b)
|
|
}
|
|
func (s *SSO) cookie(w http.ResponseWriter, name, value string, maxAge int) {
|
|
http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: s.cookiePath, HttpOnly: true, Secure: s.secure, SameSite: http.SameSiteLaxMode, MaxAge: maxAge})
|
|
}
|
|
func ssoAdmin(roles []string) bool {
|
|
for _, role := range roles {
|
|
if role == "Master Admin" || role == "FS Admin" {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
func (s *SSO) cleanupLocked() {
|
|
now := time.Now()
|
|
for k, a := range s.attempts {
|
|
if now.After(a.Expires) {
|
|
delete(s.attempts, k)
|
|
}
|
|
}
|
|
for k, v := range s.sessions {
|
|
if !now.Before(v.Expires) {
|
|
delete(s.sessions, k)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *SSO) login(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != "GET" {
|
|
w.WriteHeader(405)
|
|
return
|
|
}
|
|
state := randomSecret()
|
|
a := loginAttempt{Nonce: randomSecret(), Verifier: oauth2.GenerateVerifier(), Expires: time.Now().Add(10 * time.Minute), ReturnTo: s.base + "/files/"}
|
|
if target := r.URL.Query().Get("return"); strings.HasPrefix(target, s.base+"/") && !strings.HasPrefix(target, "//") && !strings.ContainsAny(target, "\\\r\n") && !strings.HasPrefix(target, s.base+"/auth/") && !strings.HasPrefix(target, s.base+"/login") {
|
|
a.ReturnTo = target
|
|
}
|
|
s.mu.Lock()
|
|
s.cleanupLocked()
|
|
if len(s.attempts) >= 1000 {
|
|
s.mu.Unlock()
|
|
http.Error(w, "Too many sign-in attempts", 429)
|
|
return
|
|
}
|
|
s.attempts[state] = a
|
|
s.mu.Unlock()
|
|
s.cookie(w, "fb_login", state, 600)
|
|
http.Redirect(w, r, s.oauth.AuthCodeURL(state, oidc.Nonce(a.Nonce), oauth2.S256ChallengeOption(a.Verifier)), http.StatusFound)
|
|
}
|
|
|
|
func (s *SSO) callback(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != "GET" {
|
|
w.WriteHeader(405)
|
|
return
|
|
}
|
|
if len(r.URL.Query()["state"]) != 1 || len(r.URL.Query()["code"]) != 1 {
|
|
http.Error(w, "Invalid callback parameters", 400)
|
|
return
|
|
}
|
|
state := r.URL.Query().Get("state")
|
|
c, err := r.Cookie("fb_login")
|
|
if err != nil || state == "" || c.Value != state {
|
|
http.Error(w, "Invalid sign-in state", 400)
|
|
return
|
|
}
|
|
s.mu.Lock()
|
|
a, ok := s.attempts[state]
|
|
delete(s.attempts, state)
|
|
s.mu.Unlock()
|
|
s.cookie(w, "fb_login", "", -1)
|
|
if !ok || time.Now().After(a.Expires) {
|
|
http.Error(w, "Sign-in expired. Please try again.", 400)
|
|
return
|
|
}
|
|
ctx := oidc.ClientContext(r.Context(), &http.Client{Timeout: 15 * time.Second})
|
|
token, err := s.oauth.Exchange(ctx, r.URL.Query().Get("code"), oauth2.VerifierOption(a.Verifier))
|
|
if err != nil {
|
|
http.Error(w, "SSO code exchange failed", 401)
|
|
return
|
|
}
|
|
raw, _ := token.Extra("id_token").(string)
|
|
id, err := s.verifier.Verify(ctx, raw)
|
|
if err != nil || id.Nonce != a.Nonce {
|
|
http.Error(w, "Invalid SSO identity", 401)
|
|
return
|
|
}
|
|
if err = id.VerifyAccessToken(token.AccessToken); err != nil {
|
|
http.Error(w, "Invalid SSO token binding", 401)
|
|
return
|
|
}
|
|
var claims ssoClaims
|
|
if err = id.Claims(&claims); err != nil || claims.Subject == "" {
|
|
http.Error(w, "Invalid SSO claims", 401)
|
|
return
|
|
}
|
|
if token.Expiry.IsZero() || time.Now().After(token.Expiry) {
|
|
http.Error(w, "Invalid SSO expiry", 401)
|
|
return
|
|
}
|
|
// Fetch profile data as VTNL Panel does, retaining signed identity and roles.
|
|
var metadata struct {
|
|
UserInfoURL string `json:"userinfo_endpoint"`
|
|
}
|
|
if err = s.provider.Claims(&metadata); err != nil {
|
|
http.Error(w, "Invalid SSO metadata", 401)
|
|
return
|
|
}
|
|
if metadata.UserInfoURL != "" {
|
|
profile, profileErr := s.provider.UserInfo(ctx, oauth2.StaticTokenSource(token))
|
|
if profileErr != nil || profile.Subject != claims.Subject {
|
|
http.Error(w, "Invalid SSO profile", 401)
|
|
return
|
|
}
|
|
var info ssoClaims
|
|
if err = profile.Claims(&info); err != nil {
|
|
http.Error(w, "Invalid SSO profile claims", 401)
|
|
return
|
|
}
|
|
if claims.Username == "" {
|
|
claims.Username = info.Username
|
|
}
|
|
if claims.Name == "" {
|
|
claims.Name = info.Name
|
|
}
|
|
if claims.Email == "" {
|
|
claims.Email = info.Email
|
|
}
|
|
}
|
|
identity, err := s.provisionUser(claims)
|
|
if err != nil {
|
|
http.Error(w, "Cannot provision SSO user", 500)
|
|
return
|
|
}
|
|
sid := randomSecret()
|
|
key := sha256.Sum256([]byte(sid))
|
|
s.mu.Lock()
|
|
s.cleanupLocked()
|
|
if len(s.sessions) >= 10000 {
|
|
s.mu.Unlock()
|
|
http.Error(w, "Too many sessions", 503)
|
|
return
|
|
}
|
|
if old, e := r.Cookie("fb_session"); e == nil {
|
|
delete(s.sessions, sha256.Sum256([]byte(old.Value)))
|
|
}
|
|
expires := time.Now().Add(8 * time.Hour)
|
|
s.sessions[key] = &ssoSession{Identity: identity, Expires: expires, Touched: time.Now()}
|
|
s.mu.Unlock()
|
|
s.cookie(w, "fb_session", sid, int(time.Until(expires).Seconds()))
|
|
http.Redirect(w, r, a.ReturnTo, http.StatusSeeOther)
|
|
}
|
|
|
|
func (s *SSO) provisionUser(c ssoClaims) (sessionIdentity, error) {
|
|
s.provision.Lock()
|
|
defer s.provision.Unlock()
|
|
// Stable subject IDs cannot claim a pre-existing local username or administrator.
|
|
// Namespace by issuer and subject, never by a renameable login or email.
|
|
identityHash := sha256.Sum256([]byte(s.issuer + "\x00" + c.Subject))
|
|
username := "sso:" + base64.RawURLEncoding.EncodeToString(identityHash[:])
|
|
var lookup interface{} = username
|
|
if id, ok := s.userIDs[username]; ok {
|
|
lookup = id
|
|
}
|
|
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, lookup)
|
|
if errors.Is(err, fberrors.ErrNotExist) {
|
|
st, err := s.store.Settings.Get()
|
|
if err != nil {
|
|
return sessionIdentity{}, err
|
|
}
|
|
u = &users.User{Username: username, DisplayName: c.Username, Password: "!sso-disabled", LockPassword: true}
|
|
st.Defaults.Apply(u)
|
|
u.Perm.Admin = false
|
|
u.Perm.Execute = false
|
|
u.Commands = []string{}
|
|
u.ViewMode = users.ListViewMode
|
|
derived, err := st.CreateUserHome(u, s.server.Root, false)
|
|
if err != nil {
|
|
return sessionIdentity{}, err
|
|
}
|
|
if err = s.store.Users.SaveProvisioned(u, derived); err != nil {
|
|
return sessionIdentity{}, err
|
|
}
|
|
if s.userIDs == nil {
|
|
s.userIDs = map[string]uint{}
|
|
}
|
|
s.userIDs[username] = u.ID
|
|
} else if err != nil {
|
|
return sessionIdentity{}, err
|
|
}
|
|
name := c.Username
|
|
if name == "" {
|
|
name = c.Name
|
|
}
|
|
if name == "" {
|
|
name = c.Subject
|
|
}
|
|
if u.DisplayName != name || u.ProfileName != c.Name || u.Email != c.Email {
|
|
u.DisplayName, u.ProfileName, u.Email = name, c.Name, c.Email
|
|
if err = s.store.Users.Update(u, "DisplayName", "ProfileName", "Email"); err != nil {
|
|
return sessionIdentity{}, err
|
|
}
|
|
}
|
|
return sessionIdentity{ID: u.ID, Name: name, Admin: ssoAdmin(c.Roles)}, nil
|
|
}
|
|
|
|
func (s *SSO) identify(r *http.Request) (sessionIdentity, bool) {
|
|
c, err := r.Cookie("fb_session")
|
|
if err != nil {
|
|
return sessionIdentity{}, false
|
|
}
|
|
key := sha256.Sum256([]byte(c.Value))
|
|
s.mu.Lock()
|
|
session := s.sessions[key]
|
|
s.mu.Unlock()
|
|
if session == nil {
|
|
return sessionIdentity{}, false
|
|
}
|
|
session.Lock()
|
|
defer session.Unlock()
|
|
valid := time.Now().Before(session.Expires) && time.Since(session.Touched) < 30*time.Minute
|
|
if !valid {
|
|
s.mu.Lock()
|
|
delete(s.sessions, key)
|
|
s.mu.Unlock()
|
|
return sessionIdentity{}, false
|
|
}
|
|
session.Touched = time.Now()
|
|
return session.Identity, true
|
|
}
|
|
|
|
func (s *SSO) Wrap(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
p := strings.TrimPrefix(r.URL.Path, s.base)
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.Header().Set("Referrer-Policy", "same-origin")
|
|
if strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/auth/") {
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
}
|
|
if r.Method != "GET" && r.Method != "HEAD" && r.Method != "OPTIONS" {
|
|
origin := r.Header.Get("Origin")
|
|
if (origin != "" && origin != s.origin) || (origin == "" && r.Header.Get("X-FB-Request") != "1") || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
|
http.Error(w, "Cross-origin request rejected", 403)
|
|
return
|
|
}
|
|
}
|
|
switch p {
|
|
case "/auth/login":
|
|
s.login(w, r)
|
|
return
|
|
case "/auth/callback":
|
|
s.callback(w, r)
|
|
return
|
|
case "/auth/logout":
|
|
if r.Method != "POST" {
|
|
w.WriteHeader(405)
|
|
return
|
|
}
|
|
if c, e := r.Cookie("fb_session"); e == nil {
|
|
s.mu.Lock()
|
|
delete(s.sessions, sha256.Sum256([]byte(c.Value)))
|
|
s.mu.Unlock()
|
|
}
|
|
s.cookie(w, "fb_session", "", -1)
|
|
w.WriteHeader(204)
|
|
return
|
|
case "/api/login", "/api/signup", "/api/renew", "/api/command":
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
identity, ok := s.identify(r)
|
|
if p == "/api/session" {
|
|
if r.Method != "GET" {
|
|
w.WriteHeader(405)
|
|
return
|
|
}
|
|
if !ok {
|
|
w.WriteHeader(401)
|
|
return
|
|
}
|
|
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, identity.ID)
|
|
if err != nil {
|
|
w.WriteHeader(401)
|
|
return
|
|
}
|
|
applySSOIdentity(u, identity)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(ssoUserInfo(u))
|
|
return
|
|
}
|
|
if ok {
|
|
r = r.WithContext(context.WithValue(r.Context(), identityKey{}, identity))
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func applySSOIdentity(u *users.User, i sessionIdentity) {
|
|
u.Perm.Admin = i.Admin
|
|
if i.Admin {
|
|
u.Perm = users.Permissions{Admin: true, Create: true, Rename: true, Modify: true, Delete: true, Share: true, Download: true}
|
|
}
|
|
u.Perm.Execute = false
|
|
u.LockPassword = true
|
|
u.Commands = []string{}
|
|
u.DisplayName = i.Name
|
|
}
|
|
func ssoUserInfo(u *users.User) userInfo {
|
|
return userInfo{ID: u.ID, Username: u.DisplayName, ProfileName: u.ProfileName, Email: u.Email, Locale: u.Locale, ViewMode: u.ViewMode, SingleClick: u.SingleClick, RedirectAfterCopyMove: u.RedirectAfterCopyMove, Perm: u.Perm, Commands: []string{}, LockPassword: true, HideDotfiles: u.HideDotfiles, DateFormat: u.DateFormat, AceEditorTheme: u.AceEditorTheme}
|
|
}
|