mox/webauth/admin.go
Mechiel Lukkien 0f8bf2f220
replace http basic auth for web interfaces with session cookie & csrf-based auth
the http basic auth we had was very simple to reason about, and to implement.
but it has a major downside:

there is no way to logout, browsers keep sending credentials. ideally, browsers
themselves would show a button to stop sending credentials.

a related downside: the http auth mechanism doesn't indicate for which server
paths the credentials are.

another downside: the original password is sent to the server with each
request. though sending original passwords to web servers seems to be
considered normal.

our new approach uses session cookies, along with csrf values when we can. the
sessions are server-side managed, automatically extended on each use. this
makes it easy to invalidate sessions and keeps the frontend simpler (than with
long- vs short-term sessions and refreshing). the cookies are httponly,
samesite=strict, scoped to the path of the web interface. cookies are set
"secure" when set over https. the cookie is set by a successful call to Login.
a call to Logout invalidates a session. changing a password invalidates all
sessions for a user, but keeps the session with which the password was changed
alive. the csrf value is also random, and associated with the session cookie.
the csrf must be sent as header for api calls, or as parameter for direct form
posts (where we cannot set a custom header). rest-like calls made directly by
the browser, e.g. for images, don't have a csrf protection. the csrf value is
returned by the Login api call and stored in localstorage.

api calls without credentials return code "user:noAuth", and with bad
credentials return "user:badAuth". the api client recognizes this and triggers
a login. after a login, all auth-failed api calls are automatically retried.
only for "user:badAuth" is an error message displayed in the login form (e.g.
session expired).

in an ideal world, browsers would take care of most session management. a
server would indicate authentication is needed (like http basic auth), and the
browsers uses trusted ui to request credentials for the server & path. the
browser could use safer mechanism than sending original passwords to the
server, such as scram, along with a standard way to create sessions.  for now,
web developers have to do authentication themselves: from showing the login
prompt, ensuring the right session/csrf cookies/localstorage/headers/etc are
sent with each request.

webauthn is a newer way to do authentication, perhaps we'll implement it in the
future. though hardware tokens aren't an attractive option for many users, and
it may be overkill as long as we still do old-fashioned authentication in smtp
& imap where passwords can be sent to the server.

for issue #58
2024-01-05 10:48:42 +01:00

122 lines
3.3 KiB
Go

package webauth
import (
"context"
cryptorand "crypto/rand"
"encoding/base64"
"fmt"
"os"
"strings"
"sync"
"time"
"golang.org/x/crypto/bcrypt"
"github.com/mjl-/mox/mlog"
"github.com/mjl-/mox/mox-"
"github.com/mjl-/mox/store"
)
// Admin is for admin logins, with authentication by password, and sessions only
// stored in memory only, with lifetime 12 hour after last use, with a maximum of
// 10 active sessions.
var Admin SessionAuth = &adminSessionAuth{
sessions: map[store.SessionToken]adminSession{},
}
// Good chance of fitting one working day.
const adminSessionLifetime = 12 * time.Hour
type adminSession struct {
sessionToken store.SessionToken
csrfToken store.CSRFToken
expires time.Time
}
type adminSessionAuth struct {
sync.Mutex
sessions map[store.SessionToken]adminSession
}
func (a *adminSessionAuth) login(ctx context.Context, log mlog.Log, username, password string) (bool, string, error) {
a.Lock()
defer a.Unlock()
p := mox.ConfigDirPath(mox.Conf.Static.AdminPasswordFile)
buf, err := os.ReadFile(p)
if err != nil {
return false, "", fmt.Errorf("reading password file: %v", err)
}
passwordhash := strings.TrimSpace(string(buf))
if err := bcrypt.CompareHashAndPassword([]byte(passwordhash), []byte(password)); err != nil {
return false, "", nil
}
return true, "", nil
}
func (a *adminSessionAuth) add(ctx context.Context, log mlog.Log, accountName string, loginAddress string) (sessionToken store.SessionToken, csrfToken store.CSRFToken, rerr error) {
a.Lock()
defer a.Unlock()
// Cleanup expired sessions.
for st, s := range a.sessions {
if time.Until(s.expires) < 0 {
delete(a.sessions, st)
}
}
// Ensure we have at most 10 sessions.
if len(a.sessions) > 10 {
var oldest *store.SessionToken
for _, s := range a.sessions {
if oldest == nil || s.expires.Before(a.sessions[*oldest].expires) {
oldest = &s.sessionToken
}
}
delete(a.sessions, *oldest)
}
// Generate new tokens.
var sessionData, csrfData [16]byte
if _, err := cryptorand.Read(sessionData[:]); err != nil {
return "", "", err
}
if _, err := cryptorand.Read(csrfData[:]); err != nil {
return "", "", err
}
sessionToken = store.SessionToken(base64.RawURLEncoding.EncodeToString(sessionData[:]))
csrfToken = store.CSRFToken(base64.RawURLEncoding.EncodeToString(csrfData[:]))
// Register session.
a.sessions[sessionToken] = adminSession{sessionToken, csrfToken, time.Now().Add(adminSessionLifetime)}
return sessionToken, csrfToken, nil
}
func (a *adminSessionAuth) use(ctx context.Context, log mlog.Log, accountName string, sessionToken store.SessionToken, csrfToken store.CSRFToken) (loginAddress string, rerr error) {
a.Lock()
defer a.Unlock()
s, ok := a.sessions[sessionToken]
if !ok {
return "", fmt.Errorf("unknown session")
} else if time.Until(s.expires) < 0 {
return "", fmt.Errorf("session expired")
} else if csrfToken != "" && csrfToken != s.csrfToken {
return "", fmt.Errorf("mismatch between csrf and session tokens")
}
s.expires = time.Now().Add(adminSessionLifetime)
a.sessions[sessionToken] = s
return "", nil
}
func (a *adminSessionAuth) remove(ctx context.Context, log mlog.Log, accountName string, sessionToken store.SessionToken) error {
a.Lock()
defer a.Unlock()
if _, ok := a.sessions[sessionToken]; !ok {
return fmt.Errorf("unknown session")
}
delete(a.sessions, sessionToken)
return nil
}