mirror of
https://github.com/mjl-/mox.git
synced 2025-06-28 01:48:15 +03:00

and show them in the account and admin interfaces. this should help with debugging, to find misconfigured clients, and potentially find attackers trying to login. we include details like login name, account name, protocol, authentication mechanism, ip addresses, tls connection properties, user-agent. and of course the result. we group entries by their details. repeat connections don't cause new records in the database, they just increase the count on the existing record. we keep data for at most 30 days. and we keep at most 10k entries per account. to prevent unbounded growth. for successful login attempts, we store them all for 30d. if a bad user causes so many entries this becomes a problem, it will be time to talk to the user... there is no pagination/searching yet in the admin/account interfaces. so the list may be long. we only show the 10 most recent login attempts by default. the rest is only shown on a separate page. there is no way yet to disable this. may come later, either as global setting or per account.
79 lines
1.5 KiB
Go
79 lines
1.5 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime/debug"
|
|
"time"
|
|
|
|
"github.com/mjl-/bstore"
|
|
|
|
"github.com/mjl-/mox/metrics"
|
|
"github.com/mjl-/mox/mlog"
|
|
"github.com/mjl-/mox/mox-"
|
|
"github.com/mjl-/mox/moxvar"
|
|
)
|
|
|
|
// AuthDB and AuthDBTypes are exported for ../backup.go.
|
|
var AuthDB *bstore.DB
|
|
var AuthDBTypes = []any{TLSPublicKey{}, LoginAttempt{}, LoginAttemptState{}}
|
|
|
|
// Init opens auth.db.
|
|
func Init(ctx context.Context) error {
|
|
if AuthDB != nil {
|
|
return fmt.Errorf("already initialized")
|
|
}
|
|
pkglog := mlog.New("store", nil)
|
|
p := mox.DataDirPath("auth.db")
|
|
os.MkdirAll(filepath.Dir(p), 0770)
|
|
opts := bstore.Options{Timeout: 5 * time.Second, Perm: 0660, RegisterLogger: moxvar.RegisterLogger(p, pkglog.Logger)}
|
|
var err error
|
|
AuthDB, err = bstore.Open(ctx, p, &opts, AuthDBTypes...)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
startLoginAttemptWriter(ctx)
|
|
|
|
go func() {
|
|
defer func() {
|
|
x := recover()
|
|
if x == nil {
|
|
return
|
|
}
|
|
|
|
mlog.New("store", nil).Error("unhandled panic in LoginAttemptCleanup", slog.Any("err", x))
|
|
debug.PrintStack()
|
|
metrics.PanicInc(metrics.Store)
|
|
|
|
}()
|
|
|
|
t := time.NewTicker(24 * time.Hour)
|
|
for {
|
|
err := LoginAttemptCleanup(ctx)
|
|
pkglog.Check(err, "cleaning up old historic login attempts")
|
|
|
|
select {
|
|
case <-t.C:
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
|
|
return nil
|
|
}
|
|
|
|
// Close closes auth.db.
|
|
func Close() error {
|
|
if AuthDB == nil {
|
|
return fmt.Errorf("not open")
|
|
}
|
|
err := AuthDB.Close()
|
|
AuthDB = nil
|
|
return err
|
|
}
|