Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:lock: Throttle Publish password brute-force and use constant-time comparison for the Publish auth code https://github.com/siyuan-note/siyuan/security/advisories/GHSA-v362-968x-gp2v

Danielb4ad326a9f06
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index 387213a91e..6d9d97820f 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -25,6 +25,7 @@ import (
"path"
"path/filepath"
"regexp"
+ "strconv"
"strings"
"unicode/utf8"
@@ -1608,15 +1609,15 @@ func getPublishAccess(c *gin.Context) {
func authFilePublishAccess(c *gin.Context) {
ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
-
arg, ok := util.JsonArg(c, ret)
if !ok {
+ c.JSON(http.StatusOK, ret)
return
}
ID := arg["id"].(string)
if util.InvalidIDPattern(ID, ret) {
+ c.JSON(http.StatusOK, ret)
return
}
password := arg["password"].(string)
@@ -1624,19 +1625,41 @@ func authFilePublishAccess(c *gin.Context) {
ret.Code = -1
ret.Msg = model.Conf.Language(285)
if model.IsEncryptedPublishRuntimeTarget(ID) {
+ c.JSON(http.StatusOK, ret)
+ return
+ }
+
+ // 按来源 IP 对发布密码认证进行限流,防止无限次暴力破解密码 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-v362-968x-gp2v
+ ip := c.ClientIP()
+ if retryAfter := util.AuthThrottleCheck(ip); 0 < retryAfter {
+ // 锁定期间持续记录失败,不断延长锁定时间
+ util.AuthThrottleFail(ip)
+ c.Header("Retry-After", strconv.Itoa(retryAfter))
+ ret.Msg = model.Conf.Language(354)
+ c.JSON(http.StatusTooManyRequests, ret)
return
}
publishAccess := model.GetPublishAccess()
for _, item := range publishAccess {
- if item.ID == ID {
- if item.Disable || item.Password == "" || item.Password != password {
- return
- }
- model.SetPublishAuthCookie(c, ID, password)
- ret.Code = 0
- ret.Msg = ""
+ if item.ID != ID {
+ continue
+ }
+ if item.Disable || item.Password == "" || !util.AuthCodeEquals(item.Password, password) {
+ // 恒定时间比较,避免通过响应时间差异猜测密码
+ util.AuthThrottleFail(ip)
+ c.JSON(http.StatusOK, ret)
return
}
+ util.AuthThrottleReset(ip)
+ model.SetPublishAuthCookie(c, ID, password)
+ ret.Code = 0
+ ret.Msg = ""
+ c.JSON(http.StatusOK, ret)
+ return
}
+
+ // 目标 ID 不在发布配置中,同样记录失败以限制尝试次数
+ util.AuthThrottleFail(ip)
+ c.JSON(http.StatusOK, ret)
}
diff --git a/kernel/api/filetree_test.go b/kernel/api/filetree_test.go
index ea40ff8bfc..6145e5b8fd 100644
--- a/kernel/api/filetree_test.go
+++ b/kernel/api/filetree_test.go
@@ -18,6 +18,7 @@ package api
import (
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
"os"
@@ -129,7 +130,7 @@ func TestAuthFilePublishAccessReturnsUniformFailure(t *testing.T) {
engine := gin.New()
engine.POST("/api/filetree/authFilePublishAccess", authFilePublishAccess)
- post := func(ID, inputPassword string) *httptest.ResponseRecorder {
+ post := func(ip, ID, inputPassword string) *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(
http.MethodPost,
@@ -137,6 +138,7 @@ func TestAuthFilePublishAccessReturnsUniformFailure(t *testing.T) {
strings.NewReader(`{"id":"`+ID+`","password":"`+inputPassword+`"}`),
)
request.Header.Set("Content-Type", "application/json")
+ request.RemoteAddr = ip + ":1234"
engine.ServeHTTP(recorder, request)
return recorder
}
@@ -156,9 +158,10 @@ func TestAuthFilePublishAccessReturnsUniformFailure(t *testing.T) {
{name: "encrypted notebook", ID: encryptedBoxID},
}
var failureBody string
- for _, test := range failures {
+ for i, test := range failures {
t.Run(test.name, func(t *testing.T) {
- recorder := post(test.ID, test.password)
+ // 每个失败用例使用独立的来源 IP,避免触发限流影响失败响应一致性断言
+ recorder := post(fmt.Sprintf("192.0.2.%d", 10+i), test.ID, test.password)
if cookies := recorder.Header().Values("Set-Cookie"); len(cookies) != 0 {
t.Fatalf("failed publish authentication set cookies: %v", cookies)
}
@@ -188,9 +191,9 @@ func TestAuthFilePublishAccessReturnsUniformFailure(t *testing.T) {
{name: "protected", ID: protectedID},
{name: "private", ID: privateID},
}
- for _, test := range successes {
+ for i, test := range successes {
t.Run(test.name+" success", func(t *testing.T) {
- recorder := post(test.ID, password)
+ recorder := post(fmt.Sprintf("192.0.2.%d", 100+i), test.ID, password)
response := &struct {
Code int `json:"code"`
Msg string `json:"msg"`
@@ -209,6 +212,134 @@ func TestAuthFilePublishAccessReturnsUniformFailure(t *testing.T) {
}
}
+func TestAuthFilePublishAccessThrottlesBruteForce(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ const (
+ protectedID = "20260731000003-protect"
+ password = "secret"
+ passwordWrong = "wrong"
+ passwordLocked = "Too many failed authentication attempts, please try again later"
+ )
+
+ oldDataDir := util.DataDir
+ oldPublishAccess := model.PublishAccess{}
+ if oldDataDir != "" {
+ oldPublishAccess = model.GetPublishAccess()
+ }
+ oldConf := model.Conf
+ oldLangs := util.Langs
+ util.DataDir = t.TempDir()
+ model.Conf = model.NewAppConf()
+ model.Conf.Lang = "test"
+ util.Langs = map[string]map[int]string{
+ "test": {285: "Password is incorrect", 354: passwordLocked},
+ "en": {285: "Password is incorrect", 354: passwordLocked},
+ }
+ t.Cleanup(func() {
+ util.DataDir = oldDataDir
+ model.Conf = oldConf
+ util.Langs = oldLangs
+ if oldDataDir != "" {
+ if err := model.SetPublishAccess(oldPublishAccess); err != nil {
+ t.Errorf("restore publish access failed: %v", err)
+ }
+ }
+ })
+ if err := model.SetPublishAccess(model.PublishAccess{
+ {ID: protectedID, Visible: true, Password: password},
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ engine := gin.New()
+ engine.POST("/api/filetree/authFilePublishAccess", authFilePublishAccess)
+ post := func(password string) *httptest.ResponseRecorder {
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(
+ http.MethodPost,
+ "/api/filetree/authFilePublishAccess",
+ strings.NewReader(`{"id":"`+protectedID+`","password":"`+password+`"}`),
+ )
+ request.Header.Set("Content-Type", "application/json")
+ request.RemoteAddr = "192.0.2.200:1234"
+ engine.ServeHTTP(recorder, request)
+ return recorder
+ }
+
+ const attackerIP = "192.0.2.200"
+ defer util.AuthThrottleReset(attackerIP)
+
+ // 前 5 次失败为普通失败响应,第 6 次失败触发锁定但本次仍返回普通响应(与 util.AuthThrottleFail 语义一致)
+ for i := 0; i < 6; i++ {
+ recorder := post(passwordWrong)
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("attempt %d expected %d, got %d", i+1, http.StatusOK, recorder.Code)
+ }
+ response := &struct {
+ Code int `json:"code"`
+ Msg string `json:"msg"`
+ }{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
+ t.Fatalf("unmarshal response failed: %v", err)
+ }
+ if response.Code != -1 || response.Msg != "Password is incorrect" {
+ t.Fatalf("unexpected failed publish authentication response: %s", recorder.Body.String())
+ }
+ }
+
+ // 超过阈值后返回 429 并携带 Retry-After,不再设置认证 Cookie
+ recorder := post(passwordWrong)
+ if recorder.Code != http.StatusTooManyRequests {
+ t.Fatalf("throttled attempt expected %d, got %d", http.StatusTooManyRequests, recorder.Code)
+ }
+ if "" == recorder.Header().Get("Retry-After") {
+ t.Fatal("throttled attempt should set Retry-After header")
+ }
+ response := &struct {
+ Code int `json:"code"`
+ Msg string `json:"msg"`
+ }{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
+ t.Fatalf("unmarshal response failed: %v", err)
+ }
+ if response.Code != -1 || response.Msg != passwordLocked {
+ t.Fatalf("unexpected throttled publish authentication response: %s", recorder.Body.String())
+ }
+ if cookies := recorder.Result().Cookies(); 0 < len(cookies) {
+ t.Fatalf("throttled publish authentication set cookies: %v", cookies)
+ }
+
+ // 锁定期间即使密码正确也会被拒绝
+ recorder = post(password)
+ if recorder.Code != http.StatusTooManyRequests {
+ t.Fatalf("correct password during lock expected %d, got %d", http.StatusTooManyRequests, recorder.Code)
+ }
+ if cookies := recorder.Result().Cookies(); 0 < len(cookies) {
+ t.Fatalf("correct password during lock set cookies: %v", cookies)
+ }
+
+ // 锁定解除后正确密码可认证成功
+ util.AuthThrottleReset(attackerIP)
+ recorder = post(password)
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("post-lock success expected %d, got %d", http.StatusOK, recorder.Code)
+ }
+ response = &struct {
+ Code int `json:"code"`
+ Msg string `json:"msg"`
+ }{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
+ t.Fatalf("unmarshal response failed: %v", err)
+ }
+ if response.Code != 0 || response.Msg != "" {
+ t.Fatalf("unexpected post-lock publish authentication response: %s", recorder.Body.String())
+ }
+ if cookies := recorder.Result().Cookies(); len(cookies) != 1 || cookies[0].Name != "publish-auth-"+protectedID {
+ t.Fatalf("unexpected post-lock publish authentication cookies: %v", cookies)
+ }
+}
+
func TestPublishAccessConfigurationRejectsEncryptedNotebook(t *testing.T) {
gin.SetMode(gin.TestMode)
diff --git a/kernel/api/system.go b/kernel/api/system.go
index 7d5eaf0478..f1c07df1bd 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -863,7 +863,7 @@ func setAccessAuthCode(c *gin.Context) {
// 仅校验新设置的密码,掩码回填的已有密码和清空(禁用锁屏)不做长度限制,避免用户被锁定 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-w3xh-mmmh-r54v
if !masked && 0 < len(aac) && 8 > len(aac) {
ret.Code = -1
- ret.Msg = model.Conf.Language(333)
+ ret.Msg = model.Conf.Language(355)
return
}
diff --git a/kernel/model/session.go b/kernel/model/session.go
index dfee9d6a77..9231ba401d 100644
--- a/kernel/model/session.go
+++ b/kernel/model/session.go
@@ -338,7 +338,7 @@ func CheckAuth(c *gin.Context) {
// 锁定期间持续记录失败,防止暴力破解 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-w3xh-mmmh-r54v
util.AuthThrottleFail(ip)
c.Header("Retry-After", strconv.Itoa(retryAfter))
- c.JSON(http.StatusTooManyRequests, map[string]any{"code": -1, "msg": Conf.Language(332)})
+ c.JSON(http.StatusTooManyRequests, map[string]any{"code": -1, "msg": Conf.Language(354)})
c.Abort()
return
}