Skip to content

armgit / ARTEX

Public Imported from GitHub
0

ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)

fix(server): rate-limit change-password guesses

Coff0xc389825a6838b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7f7c27b..e8bfd37 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -52,6 +52,7 @@ All notable changes to this project are documented in this file. The format is b
- **Findings CSV formula cells**: `FindingsCSV` prefixes name, class, summary, task, and other text fields that start with `=`, `+`, `-`, `@`, tab, or CR so Excel/LibreOffice do not evaluate them as formulas when the export is opened.
- **Asset service links**: the Services tab only uses an asset URL as `href` when it is `http:` or `https:`. `javascript:`, `data:`, and other schemes render as text.
- **Chat session directories**: `ChatAgent.Chat` accepts only `[A-Za-z0-9_-]` session ids (at most 64 bytes) before joining them under `<workDir>/sessions`, so `..` and path separators cannot escape that directory.
+- **Change-password rate limit**: `POST /api/auth/change-password` uses the same limiter as login, keyed by client IP and by the session token, so a stolen session cannot guess the current password without backoff.
- **ask_operator image_path**: the screenshot path must resolve inside the task working directory (`<data>/tasks/<id>`). Absolute paths, `..` segments, and symlinks that leave that directory are refused, so the tool cannot copy an arbitrary server image into the operator transcript.
- **insert_assets fail-closed**: when intercept or task allow/block rules cannot be loaded, `insert_assets` refuses the whole call instead of evaluating an empty rule set (which allowed every asset). The tool result does not include the underlying database error.
- **BlobRange length no longer wraps int64**: `offset+length > size` overflowed when length was near MaxInt64, so the cap was skipped and `make([]byte, length)` could exhaust memory. The bound is now `length > size-offset`.
diff --git a/server/auth.go b/server/auth.go
index 3b7b657..814b9d1 100644
--- a/server/auth.go
+++ b/server/auth.go
@@ -35,6 +35,8 @@ const (
// length, so passwords set under the old 8-character minimum still log in.
minPasswordRunes = 12
maxPasswordBytes = 72
+
+ pwdLimitTokenPrefix = "tok:"
)
// errDataSourceUnavailable is the uniform reply when a password-related read fails.
@@ -479,6 +481,12 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) {
writeErr(w, 401, "Unauthorized")
return
}
+ if wait := s.passwordChangeWait(r); wait > 0 {
+ secs := int((wait + time.Second - 1) / time.Second)
+ w.Header().Set("Retry-After", strconv.Itoa(secs))
+ writeErr(w, 429, fmt.Sprintf("Too many password change attempts, try again in %d seconds", secs))
+ return
+ }
var req struct {
OldPassword string `json:"old_password"`
NewPassword string `json:"new_password"`
@@ -520,10 +528,31 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) {
writeErr(w, 500, "Save failed: "+err.Error())
return
}
+ s.passwordChangeReset(r)
s.applyPasswordVersion(version)
writeJSON(w, 200, map[string]any{"ok": true})
}
+// passwordChangeWait records one authenticated change-password attempt against
+// the client IP and the session token. Either bucket can block; rotating the
+// source address with a stolen token still hits the token bucket.
+func (s *Server) passwordChangeWait(r *http.Request) time.Duration {
+ if s.pwdLimit == nil {
+ return 0
+ }
+ ip := clientIP(r, s.trustedProxies)
+ tok := pwdLimitTokenPrefix + extractToken(r)
+ return max(s.pwdLimit.allow(ip), s.pwdLimit.allow(tok))
+}
+
+func (s *Server) passwordChangeReset(r *http.Request) {
+ if s.pwdLimit == nil {
+ return
+ }
+ s.pwdLimit.reset(clientIP(r, s.trustedProxies))
+ s.pwdLimit.reset(pwdLimitTokenPrefix + extractToken(r))
+}
+
// POST /api/auth/login — validates username/password and returns a JWT.
func (s *Server) authLogin(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
diff --git a/server/auth_epoch_test.go b/server/auth_epoch_test.go
index 6ac3a9c..33af285 100644
--- a/server/auth_epoch_test.go
+++ b/server/auth_epoch_test.go
@@ -59,6 +59,7 @@ func TestChangePasswordRevokesOldTokenAndKeepsItWhenSaveFails(t *testing.T) {
m: m,
jwtKey: []byte("0123456789abcdef0123456789abcdef"),
loginLimit: newLoginLimiter(time.Now),
+ pwdLimit: newLoginLimiter(time.Now),
authHashKey: fmt.Sprintf("test.password_hash.%d", stamp),
authVersionKey: fmt.Sprintf("test.password_version.%d", stamp),
}
@@ -153,7 +154,7 @@ func TestUnreadablePasswordVersionRejectsSessions(t *testing.T) {
}
defer m.Close()
key := []byte("0123456789abcdef0123456789abcdef")
- s := &Server{m: m, jwtKey: key, loginLimit: newLoginLimiter(time.Now)}
+ s := &Server{m: m, jwtKey: key, loginLimit: newLoginLimiter(time.Now), pwdLimit: newLoginLimiter(time.Now)}
s.authVersionKey = fmt.Sprintf("test.password_version.%d", time.Now().UnixNano())
tok, err := signJWTVersion(key, 1)
if err != nil {
@@ -194,6 +195,7 @@ func TestLoginRereadsPasswordVersionWhenUnreadable(t *testing.T) {
m: m,
jwtKey: []byte("0123456789abcdef0123456789abcdef"),
loginLimit: newLoginLimiter(time.Now),
+ pwdLimit: newLoginLimiter(time.Now),
authHashKey: fmt.Sprintf("test.password_hash.%d", stamp),
authVersionKey: fmt.Sprintf("test.password_version.%d", stamp),
}
diff --git a/server/change_password_limit_test.go b/server/change_password_limit_test.go
new file mode 100644
index 0000000..6436752
--- /dev/null
+++ b/server/change_password_limit_test.go
@@ -0,0 +1,210 @@
+package server
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "golang.org/x/crypto/bcrypt"
+)
+
+const changePasswordOK = "correct-horse-1"
+
+func changePasswordRequest(remote, token string) *http.Request {
+ r := httptest.NewRequest("POST", "/api/auth/change-password", nil)
+ r.RemoteAddr = remote
+ r.Header.Set("Authorization", "Bearer "+token)
+ return r
+}
+
+func TestPasswordChangeWaitBlocksByIPAndToken(t *testing.T) {
+ clk := newFakeClock()
+ s := &Server{pwdLimit: newLoginLimiter(clk.now)}
+ const tok = "stolen-session"
+ for i := 0; i < loginMaxAttempts; i++ {
+ if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.50:40000", tok)); wait != 0 {
+ t.Fatalf("attempt %d blocked after %v", i+1, wait)
+ }
+ }
+ if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.50:40000", tok)); wait <= 0 {
+ t.Fatal("same IP and token not blocked")
+ }
+
+ s = &Server{pwdLimit: newLoginLimiter(clk.now)}
+ for i := 0; i < loginMaxAttempts; i++ {
+ remote := fmt.Sprintf("198.51.100.%d:40000", i+1)
+ if wait := s.passwordChangeWait(changePasswordRequest(remote, tok)); wait != 0 {
+ t.Fatalf("rotated IP attempt %d blocked after %v", i+1, wait)
+ }
+ }
+ if wait := s.passwordChangeWait(changePasswordRequest("203.0.113.9:40000", tok)); wait <= 0 {
+ t.Fatal("stolen token still allowed after rotating the client IP")
+ }
+
+ s = &Server{pwdLimit: newLoginLimiter(clk.now)}
+ for i := 0; i < loginMaxAttempts; i++ {
+ if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.51:40000", tok)); wait != 0 {
+ t.Fatalf("fill attempt %d blocked after %v", i+1, wait)
+ }
+ }
+ s.passwordChangeReset(changePasswordRequest("192.0.2.51:40000", tok))
+ if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.51:40000", tok)); wait != 0 {
+ t.Fatalf("after reset blocked after %v", wait)
+ }
+}
+
+func changePasswordServer(t *testing.T, clk *fakeClock) (*Server, string, func(remote, old, neu string) *httptest.ResponseRecorder) {
+ t.Helper()
+ m, err := NewManager(t.TempDir(), "")
+ if err != nil {
+ t.Skipf("postgres unavailable (%v)", err)
+ }
+ t.Cleanup(func() { m.Close() })
+
+ stamp := time.Now().UnixNano()
+ s := &Server{
+ m: m,
+ jwtKey: []byte("0123456789abcdef0123456789abcdef"),
+ loginLimit: newLoginLimiter(clk.now),
+ pwdLimit: newLoginLimiter(clk.now),
+ authHashKey: fmt.Sprintf("test.password_hash.%d", stamp),
+ authVersionKey: fmt.Sprintf("test.password_version.%d", stamp),
+ }
+ t.Cleanup(func() {
+ _, _ = m.pg.Exec(`DELETE FROM settings WHERE key=$1 OR key=$2`, s.authHashKey, s.authVersionKey)
+ })
+ hash, err := bcrypt.GenerateFromPassword([]byte(changePasswordOK), bcrypt.MinCost)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := m.pg.SetSetting(s.passwordHashKey(), string(hash)); err != nil {
+ t.Fatal(err)
+ }
+ s.applyPasswordVersion(0)
+ tok, err := signJWTVersion(s.jwtKey, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ post := func(remote, old, neu string) *httptest.ResponseRecorder {
+ body := fmt.Sprintf(`{"old_password":%q,"new_password":%q}`, old, neu)
+ r := httptest.NewRequest("POST", "/api/auth/change-password", strings.NewReader(body))
+ r.RemoteAddr = remote
+ r.Header.Set("Authorization", "Bearer "+tok)
+ w := httptest.NewRecorder()
+ s.authChangePassword(w, r)
+ return w
+ }
+ return s, tok, post
+}
+
+func TestChangePasswordRateLimitReturns429WithRetryAfter(t *testing.T) {
+ clk := newFakeClock()
+ _, _, post := changePasswordServer(t, clk)
+ const ip = "192.0.2.40:40000"
+ for i := 0; i < loginMaxAttempts; i++ {
+ if w := post(ip, "wrong-password-xx", "correct-horse-9"); w.Code != 401 {
+ t.Fatalf("attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String())
+ }
+ }
+ w := post(ip, changePasswordOK, "correct-horse-9")
+ if w.Code != 429 {
+ t.Fatalf("status=%d want 429; body=%s", w.Code, w.Body.String())
+ }
+ if got := w.Header().Get("Retry-After"); got != "60" {
+ t.Fatalf("Retry-After=%q want 60", got)
+ }
+ var body struct {
+ Error string `json:"error"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Error == "" {
+ t.Fatalf("want a JSON error body, got %s (err=%v)", w.Body.String(), err)
+ }
+}
+
+func TestChangePasswordRateLimitFollowsStolenTokenAcrossIPs(t *testing.T) {
+ clk := newFakeClock()
+ _, _, post := changePasswordServer(t, clk)
+ for i := 0; i < loginMaxAttempts; i++ {
+ remote := fmt.Sprintf("198.51.100.%d:40000", i+1)
+ if w := post(remote, "wrong-password-xx", "correct-horse-9"); w.Code != 401 {
+ t.Fatalf("attempt %d from %s: status=%d want 401; body=%s", i+1, remote, w.Code, w.Body.String())
+ }
+ }
+ if w := post("203.0.113.9:40000", changePasswordOK, "correct-horse-9"); w.Code != 429 {
+ t.Fatalf("rotated IP: status=%d want 429; body=%s", w.Code, w.Body.String())
+ }
+}
+
+func TestChangePasswordSuccessResetsCounter(t *testing.T) {
+ clk := newFakeClock()
+ s, tok, post := changePasswordServer(t, clk)
+ const ip = "192.0.2.41:40000"
+ for i := 0; i < loginMaxAttempts-1; i++ {
+ if w := post(ip, "wrong-password-xx", "correct-horse-9"); w.Code != 401 {
+ t.Fatalf("attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String())
+ }
+ }
+ if w := post(ip, changePasswordOK, "correct-horse-2"); w.Code != 200 {
+ t.Fatalf("status=%d want 200; body=%s", w.Code, w.Body.String())
+ }
+ if s.sessionOK(tok) {
+ t.Fatal("token from before the password change is still accepted")
+ }
+
+ w := httptest.NewRecorder()
+ login := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"username":"ARTEX","password":"correct-horse-2"}`))
+ login.RemoteAddr = ip
+ s.authLogin(w, login)
+ if w.Code != 200 {
+ t.Fatalf("login after change: status=%d body=%s", w.Code, w.Body.String())
+ }
+ var issued struct {
+ Token string `json:"token"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &issued); err != nil || issued.Token == "" {
+ t.Fatalf("login token: %v body=%s", err, w.Body.String())
+ }
+
+ post2 := func(old, neu string) *httptest.ResponseRecorder {
+ body := fmt.Sprintf(`{"old_password":%q,"new_password":%q}`, old, neu)
+ r := httptest.NewRequest("POST", "/api/auth/change-password", strings.NewReader(body))
+ r.RemoteAddr = ip
+ r.Header.Set("Authorization", "Bearer "+issued.Token)
+ rec := httptest.NewRecorder()
+ s.authChangePassword(rec, r)
+ return rec
+ }
+ for i := 0; i < loginMaxAttempts; i++ {
+ if w := post2("wrong-password-xx", "correct-horse-9"); w.Code != 401 {
+ t.Fatalf("after reset attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String())
+ }
+ }
+ if w := post2("wrong-password-xx", "correct-horse-9"); w.Code != 429 {
+ t.Fatalf("after reset: status=%d want 429; body=%s", w.Code, w.Body.String())
+ }
+}
+
+func TestChangePasswordUnauthenticatedDoesNotCount(t *testing.T) {
+ clk := newFakeClock()
+ s, _, post := changePasswordServer(t, clk)
+ const ip = "192.0.2.42:40000"
+ body := `{"old_password":"wrong-password-xx","new_password":"correct-horse-9"}`
+ for i := 0; i < loginMaxAttempts+1; i++ {
+ r := httptest.NewRequest("POST", "/api/auth/change-password", strings.NewReader(body))
+ r.RemoteAddr = ip
+ r.Header.Set("Authorization", "Bearer not-a-token")
+ w := httptest.NewRecorder()
+ s.authChangePassword(w, r)
+ if w.Code != 401 {
+ t.Fatalf("unauthenticated attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String())
+ }
+ }
+ if w := post(ip, "wrong-password-xx", "correct-horse-9"); w.Code != 401 {
+ t.Fatalf("counted unauthenticated attempts: status=%d body=%s", w.Code, w.Body.String())
+ }
+}
diff --git a/server/login_limit_test.go b/server/login_limit_test.go
index d0a033a..790a358 100644
--- a/server/login_limit_test.go
+++ b/server/login_limit_test.go
@@ -36,7 +36,7 @@ func loginServer(t *testing.T, clk *fakeClock) (*Server, func(remote, password s
}
return string(hash), true, nil
}
- s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef"), loginLimit: newLoginLimiter(clk.now)}
+ s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef"), loginLimit: newLoginLimiter(clk.now), pwdLimit: newLoginLimiter(clk.now)}
post := func(remote, password string, hdr map[string]string) *httptest.ResponseRecorder {
body := fmt.Sprintf(`{"username":"ARTEX","password":%q}`, password)
r := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(body))
diff --git a/server/server.go b/server/server.go
index baf4423..5da030f 100644
--- a/server/server.go
+++ b/server/server.go
@@ -66,6 +66,7 @@ type Server struct {
authVersionKey string
loginLimit *loginLimiter // per-IP attempt limit on POST /api/auth/login
+ pwdLimit *loginLimiter // attempt limit on POST /api/auth/change-password (IP + session token)
trustedProxies []netip.Prefix // ARTEX_TRUSTED_PROXIES; see clientIP
// concMu serializes concurrency-cap decisions (admission + reconcile) so a
@@ -182,7 +183,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
profChatAgents: map[int64]*agent.ChatAgent{},
provByProfile: map[int64]*provEntry{},
taskAgents: map[string]*taskAgentBundle{}, archiveWake: make(chan struct{}, 1),
- loginLimit: newLoginLimiter(time.Now)}
+ loginLimit: newLoginLimiter(time.Now), pwdLimit: newLoginLimiter(time.Now)}
s.llmHealth, s.llmHealthSync = newLLMHealthRegistry(ctx, m.pg)
for _, o := range opts {
o(s)