ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)
Go aiai-agentsautonomous-agentsbug-bountydockergolanglinuxllmmcpnextjspenetration-testingpentestpostgresqlreareactred-teamsecuritysecurity-automationsqlitetypescript
Reject sessions issued before a password change.
protonmatter26a7bbec377e
diff --git a/server/auth.go b/server/auth.goindex b76a1d2..28ba185 100644--- a/server/auth.go+++ b/server/auth.go@@ -19,13 +19,15 @@ import ("golang.org/x/crypto/bcrypt""github.com/Autumn-27/artex/config"+ "github.com/Autumn-27/artex/db")const (- jwtKeyFilename = "jwt.key"- authPassKey = "auth.password_hash"- jwtTTL = 7 * 24 * time.Hour- keyChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"+ jwtKeyFilename = "jwt.key"+ authPassKey = "auth.password_hash"+ authPwdEpochKey = "auth.password_epoch"+ jwtTTL = 7 * 24 * time.Hour+ keyChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"// The lower bound matches the setup page's frontend validation — validation that// lives only in the frontend is as good as none: hitting the API directly bypasses@@ -167,15 +169,24 @@ func signJWT(key []byte) (string, error) {}).SignedString(key)}-// verifyJWT returns true when tokenStr is a valid, non-expired HS256 token.-func verifyJWT(tokenStr string, key []byte) bool {- t, err := jwt.Parse(tokenStr, func(t *jwt.Token) (any, error) {+// verifyJWT returns true when tokenStr is a valid, non-expired HS256 token+// issued at or after notBefore. notBefore is Unix seconds; 0 means no cutoff,+// so a deployment that has never stored a password epoch keeps existing sessions.+func verifyJWT(tokenStr string, key []byte, notBefore int64) bool {+ claims := &jwt.RegisteredClaims{}+ t, err := jwt.ParseWithClaims(tokenStr, claims, func(t *jwt.Token) (any, error) {if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {return nil, fmt.Errorf("unexpected signing method")}return key, nil})- return err == nil && t.Valid+ if err != nil || !t.Valid {+ return false+ }+ if notBefore > 0 && (claims.IssuedAt == nil || claims.IssuedAt.Unix() < notBefore) {+ return false+ }+ return true}// jwtSubject returns the subject of tokenStr when it is a valid, non-expired@@ -197,7 +208,11 @@ func jwtSubject(tokenStr string, key []byte) string {// approver is who a human decision is recorded for: the subject of the// request's session token.func (s *Server) approver(r *http.Request) string {- return jwtSubject(extractToken(r), s.jwtKey)+ tok := extractToken(r)+ if !verifyJWT(tok, s.jwtKey, s.pwdEpoch.Load()) {+ return ""+ }+ return jwtSubject(tok, s.jwtKey)}// extractToken reads the JWT from Authorization: Bearer header,@@ -226,7 +241,7 @@ func (s *Server) requireAuth(h http.Handler) http.Handler {writeErr(w, 401, "Unauthorized")return}- if !verifyJWT(tok, s.jwtKey) {+ if !verifyJWT(tok, s.jwtKey, s.pwdEpoch.Load()) {writeErr(w, 401, "token is invalid or expired")return}@@ -258,15 +273,72 @@ func (s *Server) initSetupToken() {if s.m == nil || s.m.pg == nil {return}- if hash, _, err := s.m.pg.GetSetting(authPassKey); err == nil && hash != "" {+ var hash string+ var err error+ for attempt := 1; attempt <= 3; attempt++ {+ var ok bool+ hash, ok, err = s.m.pg.GetSetting(authPassKey)+ if err == nil {+ if ok && hash != "" {+ return+ }+ break+ }+ log.Printf("[auth] password lookup attempt %d/3: %v", attempt, err)+ if attempt < 3 {+ time.Sleep(time.Duration(attempt) * 100 * time.Millisecond)+ }+ }+ if err != nil {+ log.Printf("[auth] password lookup failed; not issuing a setup token: %v", err)return}buf := make([]byte, 16)if _, err := rand.Read(buf); err != nil {log.Fatalf("[auth] generate setup token: %v", err)}- s.setupToken = hex.EncodeToString(buf)- log.Printf("[auth] no admin password is set. Setup token for the /setup page: %s", s.setupToken)+ token := hex.EncodeToString(buf)+ s.setupMu.Lock()+ s.setupToken = token+ s.setupMu.Unlock()+ log.Printf("[auth] no admin password is set. Setup token for the /setup page: %s", token)+}++// loadPwdEpoch reads auth.password_epoch. A missing key leaves the cutoff at+// zero, which accepts every valid token.+func (s *Server) loadPwdEpoch() {+ if s.m == nil || s.m.pg == nil {+ return+ }+ raw, ok, err := s.m.pg.GetSetting(authPwdEpochKey)+ if err != nil {+ log.Printf("[auth] password epoch: %v", err)+ return+ }+ if !ok || raw == "" {+ return+ }+ n, err := strconv.ParseInt(raw, 10, 64)+ if err != nil {+ log.Printf("[auth] password epoch %q: %v", raw, err)+ return+ }+ s.pwdEpoch.Store(n)+}++// bumpPwdEpoch records the current second as the oldest token that is still+// valid. A token signed in that same second still passes. A failed write leaves+// the previous cutoff in place and is logged; the password change itself stands.+func (s *Server) bumpPwdEpoch(pg *db.DB) {+ if pg == nil {+ return+ }+ epoch := time.Now().Unix()+ if err := pg.SetSetting(authPwdEpochKey, strconv.FormatInt(epoch, 10)); err != nil {+ log.Printf("[auth] save password epoch: %v", err)+ return+ }+ s.pwdEpoch.Store(epoch)}// checkSetupToken compares got with the active setup token in constant time.@@ -330,6 +402,7 @@ func (s *Server) authInit(w http.ResponseWriter, r *http.Request) {s.setupMu.Lock()s.setupToken = ""s.setupMu.Unlock()+ s.bumpPwdEpoch(pg)tok, err := signJWT(s.jwtKey)if err != nil {writeErr(w, 500, "token generation failed")@@ -346,7 +419,7 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) {if pg == nil {return}- if !verifyJWT(extractToken(r), s.jwtKey) {+ if !verifyJWT(extractToken(r), s.jwtKey, s.pwdEpoch.Load()) {writeErr(w, 401, "Unauthorized")return}@@ -388,6 +461,9 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) {writeErr(w, 500, "Save failed: "+err.Error())return}+ // Sessions issued before this second stop working. This response does not+ // include a replacement token; the next request asks for a new login.+ s.bumpPwdEpoch(pg)writeJSON(w, 200, map[string]any{"ok": true})}diff --git a/server/auth_epoch_test.go b/server/auth_epoch_test.gonew file mode 100644index 0000000..14e5386--- /dev/null+++ b/server/auth_epoch_test.go@@ -0,0 +1,23 @@+package server++import (+ "testing"+ "time"+)++func TestTokenBeforePasswordEpochIsRejected(t *testing.T) {+ key := []byte("0123456789abcdef0123456789abcdef")+ tok, err := signJWT(key)+ if err != nil {+ t.Fatal(err)+ }+ if !verifyJWT(tok, key, 0) {+ t.Fatal("a token with no password epoch must be accepted")+ }+ if verifyJWT(tok, key, time.Now().Add(time.Minute).Unix()) {+ t.Fatal("a token issued before the password epoch must be rejected")+ }+ if !verifyJWT(tok, key, time.Now().Add(-time.Minute).Unix()) {+ t.Fatal("a token issued after the password epoch must be accepted")+ }+}diff --git a/server/login_limit.go b/server/login_limit.goindex 51dec5a..fcc0d1e 100644--- a/server/login_limit.go+++ b/server/login_limit.go@@ -105,16 +105,34 @@ func (l *loginLimiter) sweep(now time.Time) {}}-// evictOldest drops the least recently seen entry to stay under loginMaxEntries.+// evictOldest drops the least recently seen entry that is not inside a block.+// A block that is still running stays, so filling the map cannot clear an+// active lockout. When every entry is blocked, the one whose block ends soonest+// is the one that goes.func (l *loginLimiter) evictOldest() {+ now := l.now()var oldest stringvar at time.Time+ found := falsefor ip, e := range l.entries {- if oldest == "" || e.lastSeen.Before(at) {- oldest, at = ip, e.lastSeen+ if now.Before(e.blockedUntil) {+ continue+ }+ if !found || e.lastSeen.Before(at) {+ oldest, at, found = ip, e.lastSeen, true}}- delete(l.entries, oldest)+ if !found {+ var until time.Time+ for ip, e := range l.entries {+ if oldest == "" || e.blockedUntil.Before(until) {+ oldest, until = ip, e.blockedUntil+ }+ }+ }+ if oldest != "" {+ delete(l.entries, oldest)+ }}// peerIP is the host part of the TCP peer address.diff --git a/server/login_limit_test.go b/server/login_limit_test.goindex 255b64c..d0a033a 100644--- a/server/login_limit_test.go+++ b/server/login_limit_test.go@@ -274,6 +274,36 @@ func TestLoginLimiterCapsEntries(t *testing.T) {}}+func TestEvictOldestKeepsBlockedEntries(t *testing.T) {+ clk := newFakeClock()+ l := newLoginLimiter(clk.now)+ now := clk.now()+ l.entries["blocked"] = &loginEntry{lastSeen: now.Add(-2 * time.Hour), blockedUntil: now.Add(time.Hour), block: time.Minute}+ l.entries["idle"] = &loginEntry{lastSeen: now.Add(-time.Hour)}+ l.evictOldest()+ if _, ok := l.entries["blocked"]; !ok {+ t.Fatal("evicted a blocked address while an idle one existed")+ }+ if _, ok := l.entries["idle"]; ok {+ t.Fatal("kept the idle address")+ }+}++func TestEvictOldestDropsSoonestBlockWhenAllBlocked(t *testing.T) {+ clk := newFakeClock()+ l := newLoginLimiter(clk.now)+ now := clk.now()+ l.entries["long"] = &loginEntry{lastSeen: now, blockedUntil: now.Add(2 * time.Hour)}+ l.entries["short"] = &loginEntry{lastSeen: now.Add(-time.Hour), blockedUntil: now.Add(time.Minute)}+ l.evictOldest()+ if _, ok := l.entries["short"]; ok {+ t.Fatal("kept the block that ends sooner")+ }+ if _, ok := l.entries["long"]; !ok {+ t.Fatal("evicted the longer block")+ }+}+func TestHealthHidesVersionWithoutToken(t *testing.T) {key := []byte("0123456789abcdef0123456789abcdef")s := &Server{jwtKey: key}diff --git a/server/server.go b/server/server.goindex aa88728..f6b468c 100644--- a/server/server.go+++ b/server/server.go@@ -19,6 +19,7 @@ import ("strconv""strings""sync"+ "sync/atomic""time""github.com/Autumn-27/artex/agent"@@ -53,6 +54,10 @@ type Server struct {setupMu sync.MutexsetupToken string // one-time token POST /api/auth/init requires; empty when none is active+ // pwdEpoch is auth.password_epoch in Unix seconds. Zero means the setting+ // is absent and every valid token is accepted. A token issued before the+ // stored second is rejected.+ pwdEpoch atomic.Int64loginLimit *loginLimiter // per-IP attempt limit on POST /api/auth/logintrustedProxies []netip.Prefix // ARTEX_TRUSTED_PROXIES; see clientIP@@ -170,6 +175,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDio(s)}s.initSetupToken()+ s.loadPwdEpoch()s.initSideQuestions()// Circuit-breaker thresholds/cooldowns are hot parameters on the failure path; push the global retry policy to the Registry once at startup,// and again on every policy save (saveLLMRetryPolicy).@@ -1033,7 +1039,7 @@ func (s *Server) Handler() http.Handler {// with a valid token gets the service name and version; the web UI's top bar// reads the version, and sends its token.func (s *Server) health(w http.ResponseWriter, r *http.Request) {- if !verifyJWT(extractToken(r), s.jwtKey) {+ if !verifyJWT(extractToken(r), s.jwtKey, s.pwdEpoch.Load()) {writeJSON(w, 200, map[string]any{"ok": true})return}diff --git a/web/src/lib/api.ts b/web/src/lib/api.tsindex 76bb2c8..3220292 100644--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@ -181,7 +181,9 @@ export async function http<T>(path: string, init?: RequestInit): Promise<T> {// to the Go backend on :8787, whose CORS is open.//// Override either default with NEXT_PUBLIC_SSE_BASE (set it to "" to force same-origin).-// Token is appended as ?token= because SSE can't carry cookies cross-origin.+// A same-origin stream sends the artex_token cookie. The query token is added only+// when base is non-empty, which is the dev connection to :8787: that origin cannot+// send the cookie.// mockReport returns a canned Markdown report for the demo.function mockReport(_task?: string): string {return `# ARTEX Penetration Test Report — Acme Corp@@ -211,6 +213,9 @@ export function sseUrl(path: string): string {(process.env.NODE_ENV !== "production" && typeof window !== "undefined"? `${window.location.protocol}//${window.location.hostname}:8787`: "");+ if (!base) {+ return path;+ }const token = getToken();const sep = path.includes("?") ? "&" : "?";return token ? `${base}${path}${sep}token=${encodeURIComponent(token)}` : `${base}${path}`;