Skip to content

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

:lock: Reject cross-site browser requests and prevent network proxy response sniffing https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743

Daniel9373941bebf9
diff --git a/kernel/api/broadcast.go b/kernel/api/broadcast.go
index f0c20e797a..d7c594ef28 100644
--- a/kernel/api/broadcast.go
+++ b/kernel/api/broadcast.go
@@ -415,7 +415,7 @@ func ConstructBroadcastChannel(channel string) *BroadcastChannel {
websocket := melody.New()
// 校验 Origin,防止跨站 WebSocket 劫持(CSWSH) https://github.com/siyuan-note/siyuan/security/advisories/GHSA-3cc2-h3v6-rqpq
websocket.Upgrader.CheckOrigin = func(r *http.Request) bool {
- return util.IsSessionOriginAllowed(r.Header.Get("Origin"), r.Host)
+ return util.IsSessionOriginAllowedRequest(r)
}
websocket.Config.MaxMessageSize = 1024 * 1024 * 128 // 128 MiB
diff --git a/kernel/api/network.go b/kernel/api/network.go
index 48c5df343d..bc85c76560 100644
--- a/kernel/api/network.go
+++ b/kernel/api/network.go
@@ -430,6 +430,15 @@ func forwardResponseHeaders(dst http.Header, src http.Header) {
}
}
+// secureProxyResponseHeaders 为代理响应设置安全头:禁用内容嗅探并强制不可执行类型,
+// 防止上游可控内容被浏览器渲染为 HTML 造成同源脚本执行
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743
+func secureProxyResponseHeaders(w gin.ResponseWriter) {
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.Header().Set("Content-Type", "application/octet-stream")
+ w.Header().Set("Content-Disposition", "attachment")
+}
+
// httpProxy proxies an HTTP request to a remote HTTP endpoint.
//
// Query params:
@@ -481,6 +490,7 @@ func httpProxy(c *gin.Context) {
}
defer resp.Body.Close()
+ secureProxyResponseHeaders(c.Writer)
forwardResponseHeaders(c.Writer.Header(), resp.Header)
c.Writer.WriteHeader(resp.StatusCode)
if _, err := io.Copy(c.Writer, resp.Body); err != nil {
@@ -526,7 +536,7 @@ func wsProxy(c *gin.Context) {
upgrader := websocket.Upgrader{
// 校验 Origin,防止跨站 WebSocket 劫持(CSWSH) https://github.com/siyuan-note/siyuan/security/advisories/GHSA-3cc2-h3v6-rqpq
CheckOrigin: func(r *http.Request) bool {
- return util.IsSessionOriginAllowed(r.Header.Get("Origin"), r.Host)
+ return util.IsSessionOriginAllowedRequest(r)
},
}
clientConn, upgradeErr := upgrader.Upgrade(c.Writer, c.Request, upgradeHeaders)
@@ -629,6 +639,7 @@ func esProxy(c *gin.Context) {
}
defer resp.Body.Close()
+ secureProxyResponseHeaders(c.Writer)
forwardResponseHeaders(c.Writer.Header(), resp.Header)
c.Writer.WriteHeader(resp.StatusCode)
diff --git a/kernel/api/network_test.go b/kernel/api/network_test.go
index d81b8383ff..6e7fabbfe4 100644
--- a/kernel/api/network_test.go
+++ b/kernel/api/network_test.go
@@ -3,6 +3,7 @@ package api
import (
"bytes"
"compress/gzip"
+ "encoding/base64"
"errors"
"io"
"net/http"
@@ -10,6 +11,7 @@ import (
"strconv"
"testing"
+ "github.com/gin-gonic/gin"
"github.com/imroc/req/v3"
)
@@ -65,6 +67,46 @@ func TestConfigureForwardProxyResponseEncoding(t *testing.T) {
}
}
+// TestHTTPProxyResponseSecurityHeaders 验证 /api/network/proxy 响应禁用内容嗅探并强制不可执行类型,
+// 防止上游可控内容被浏览器渲染为 HTML 造成同源脚本执行
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743
+func TestHTTPProxyResponseSecurityHeaders(t *testing.T) {
+ upstreamBody := []byte("<html><body>SNIFFED-AS-HTML<script>alert(1)</script></body></html>")
+
+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
+ writer.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = writer.Write(upstreamBody)
+ }))
+ defer server.Close()
+
+ engine := gin.New()
+ engine.Any("/api/network/proxy", httpProxy)
+
+ request := httptest.NewRequest(http.MethodGet,
+ "/api/network/proxy?u="+base64.RawURLEncoding.EncodeToString([]byte(server.URL)), nil)
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, request)
+
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", recorder.Code, http.StatusOK)
+ }
+ if recorder.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatalf("X-Content-Type-Options = %q, want nosniff", recorder.Header().Get("X-Content-Type-Options"))
+ }
+ if recorder.Header().Get("Content-Type") != "application/octet-stream" {
+ t.Fatalf("Content-Type = %q, want application/octet-stream", recorder.Header().Get("Content-Type"))
+ }
+ if recorder.Header().Get("Content-Disposition") != "attachment" {
+ t.Fatalf("Content-Disposition = %q, want attachment", recorder.Header().Get("Content-Disposition"))
+ }
+ if recorder.Header().Get("Siyuan-Proxy-Content-Type") != "text/html; charset=utf-8" {
+ t.Fatalf("Siyuan-Proxy-Content-Type = %q, want upstream content type", recorder.Header().Get("Siyuan-Proxy-Content-Type"))
+ }
+ if !bytes.Equal(recorder.Body.Bytes(), upstreamBody) {
+ t.Fatalf("body = %q, want %q", recorder.Body.String(), upstreamBody)
+ }
+}
+
func TestForwardProxyResponseSizeLimit(t *testing.T) {
const limit int64 = 64
body := bytes.Repeat([]byte("a"), int(limit)+1)
diff --git a/kernel/model/session.go b/kernel/model/session.go
index ee78a18bc4..43c237ccad 100644
--- a/kernel/model/session.go
+++ b/kernel/model/session.go
@@ -253,6 +253,14 @@ func CheckAuth(c *gin.Context) {
return
}
+ // 浏览器标记的跨站请求直接拒绝,防止跨站 GET 导航不带 Origin 时绕过校验
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743
+ if util.IsCrossSiteFetchSite(c.GetHeader("Sec-Fetch-Site")) {
+ c.JSON(http.StatusUnauthorized, map[string]any{"code": -1, "msg": "Auth failed: cross-site requests are not allowed\n出于安全考虑,拒绝跨站请求"})
+ c.Abort()
+ return
+ }
+
// Authenticate requests with the Origin header other than 127.0.0.1 https://github.com/siyuan-note/siyuan/issues/9180
clientIP := c.ClientIP()
host := c.Request.Host
@@ -313,7 +321,9 @@ func CheckAuth(c *gin.Context) {
workspaceSession := util.GetWorkspaceSession(session)
if IsWorkspaceSessionAuthenticated(workspaceSession) {
// 校验 Origin 防止跨站请求伪造 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hhm2-g993-p656
- if !util.IsSessionOriginAllowed(c.GetHeader("Origin"), c.Request.Host) {
+ // 同时拒绝浏览器标记的跨站请求,防止跨站 GET 导航不带 Origin 时绕过校验
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743
+ if !util.IsSessionOriginAllowedRequest(c.Request) {
logging.LogWarnf("invalid Origin [%s] for session auth [ip=%s]", c.GetHeader("Origin"), c.ClientIP())
c.JSON(http.StatusUnauthorized, map[string]any{"code": -1, "msg": "Auth failed: invalid Origin"})
c.Abort()
diff --git a/kernel/model/session_test.go b/kernel/model/session_test.go
index a27a7aafd7..9640c0b204 100644
--- a/kernel/model/session_test.go
+++ b/kernel/model/session_test.go
@@ -139,6 +139,110 @@ func TestIsLocalRequest(t *testing.T) {
}
}
+// TestCheckAuthCrossSiteFetchSite 验证未设置锁屏密码时拒绝浏览器标记的跨站请求,
+// 防止跨站 GET 导航不带 Origin 绕过校验
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743
+func TestCheckAuthCrossSiteFetchSite(t *testing.T) {
+ originalConf := Conf
+ Conf = NewAppConf()
+ t.Cleanup(func() { Conf = originalConf })
+
+ engine := gin.New()
+ engine.GET("/api/test", CheckAuth, func(c *gin.Context) {
+ c.Status(http.StatusNoContent)
+ })
+
+ newRequest := func(site string) *httptest.ResponseRecorder {
+ request := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:6806/api/test", nil)
+ request.RemoteAddr = "127.0.0.1:1234"
+ if "" != site {
+ request.Header.Set("Sec-Fetch-Site", site)
+ }
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, request)
+ return recorder
+ }
+
+ if recorder := newRequest("cross-site"); recorder.Code != http.StatusUnauthorized {
+ t.Fatalf("cross-site status = %d, want %d", recorder.Code, http.StatusUnauthorized)
+ }
+ if recorder := newRequest("same-site"); recorder.Code != http.StatusUnauthorized {
+ t.Fatalf("same-site status = %d, want %d", recorder.Code, http.StatusUnauthorized)
+ }
+ if recorder := newRequest("same-origin"); recorder.Code != http.StatusNoContent {
+ t.Fatalf("same-origin status = %d, want %d", recorder.Code, http.StatusNoContent)
+ }
+ if recorder := newRequest("none"); recorder.Code != http.StatusNoContent {
+ t.Fatalf("none status = %d, want %d", recorder.Code, http.StatusNoContent)
+ }
+ if recorder := newRequest(""); recorder.Code != http.StatusNoContent {
+ t.Fatalf("absent header status = %d, want %d", recorder.Code, http.StatusNoContent)
+ }
+}
+
+// TestCheckAuthSessionCrossSiteFetchSite 验证会话认证下拒绝浏览器标记的跨站 GET 导航请求
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743
+func TestCheckAuthSessionCrossSiteFetchSite(t *testing.T) {
+ originalConf := Conf
+ originalWorkspaceDir := util.WorkspaceDir
+ Conf = NewAppConf()
+ Conf.AccessAuthCode = "test-access-auth-code"
+ util.WorkspaceDir = "test-workspace"
+ t.Cleanup(func() {
+ Conf = originalConf
+ util.WorkspaceDir = originalWorkspaceDir
+ })
+
+ engine := gin.New()
+ store := cookie.NewStore([]byte("test-session-cookie-key"))
+ engine.Use(ginSessions.Sessions("siyuan", store))
+ engine.GET("/login", func(c *gin.Context) {
+ session := util.GetSession(c)
+ workspaceSession := util.GetWorkspaceSession(session)
+ workspaceSession.AccessAuthCode = Conf.AccessAuthCode
+ if err := session.Save(c); err != nil {
+ c.Status(http.StatusInternalServerError)
+ return
+ }
+ c.Status(http.StatusNoContent)
+ })
+ engine.GET("/api/test", CheckAuth, func(c *gin.Context) {
+ c.Status(http.StatusNoContent)
+ })
+
+ loginRequest := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:6806/login", nil)
+ loginRequest.RemoteAddr = "127.0.0.1:1234"
+ loginRecorder := httptest.NewRecorder()
+ engine.ServeHTTP(loginRecorder, loginRequest)
+ if loginRecorder.Code != http.StatusNoContent {
+ t.Fatalf("login status = %d, want %d", loginRecorder.Code, http.StatusNoContent)
+ }
+
+ request := func(site string) *httptest.ResponseRecorder {
+ request := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:6806/api/test", nil)
+ request.RemoteAddr = "127.0.0.1:1234"
+ if "" != site {
+ request.Header.Set("Sec-Fetch-Site", site)
+ }
+ for _, responseCookie := range loginRecorder.Result().Cookies() {
+ request.AddCookie(responseCookie)
+ }
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, request)
+ return recorder
+ }
+
+ if recorder := request("cross-site"); recorder.Code != http.StatusUnauthorized {
+ t.Fatalf("cross-site status = %d, want %d", recorder.Code, http.StatusUnauthorized)
+ }
+ if recorder := request("same-origin"); recorder.Code != http.StatusNoContent {
+ t.Fatalf("same-origin status = %d, want %d", recorder.Code, http.StatusNoContent)
+ }
+ if recorder := request(""); recorder.Code != http.StatusNoContent {
+ t.Fatalf("absent header status = %d, want %d", recorder.Code, http.StatusNoContent)
+ }
+}
+
// TestCheckAuthRemoteSessionOrigin 验证局域网浏览器登录后,同源 POST 请求可通过会话鉴权。
func TestCheckAuthRemoteSessionOrigin(t *testing.T) {
originalConf := Conf
diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.go
index 5bafd4bcf3..2bf6e65c2e 100644
--- a/kernel/plugin/plugin.go
+++ b/kernel/plugin/plugin.go
@@ -1004,7 +1004,7 @@ func (p *KernelPlugin) handleWebSocketRequest(c *gin.Context, request *Request,
upgrader := gws.NewUpgrader(h, &gws.ServerOption{
// 校验 Origin,防止跨站 WebSocket 劫持(CSWSH) https://github.com/siyuan-note/siyuan/security/advisories/GHSA-3cc2-h3v6-rqpq
Authorize: func(r *http.Request, _ gws.SessionStorage) bool {
- return util.IsSessionOriginAllowed(r.Header.Get("Origin"), r.Host)
+ return util.IsSessionOriginAllowedRequest(r)
},
})
diff --git a/kernel/plugin/rpc.go b/kernel/plugin/rpc.go
index 1e085d2f05..fc15efc084 100644
--- a/kernel/plugin/rpc.go
+++ b/kernel/plugin/rpc.go
@@ -355,7 +355,7 @@ func HandleRpcWebSocket(c *gin.Context) {
upgrader := gws.NewUpgrader(h, &gws.ServerOption{
// 校验 Origin,防止跨站 WebSocket 劫持(CSWSH) https://github.com/siyuan-note/siyuan/security/advisories/GHSA-3cc2-h3v6-rqpq
Authorize: func(r *http.Request, _ gws.SessionStorage) bool {
- return util.IsSessionOriginAllowed(r.Header.Get("Origin"), r.Host)
+ return util.IsSessionOriginAllowedRequest(r)
},
})
socket, err := upgrader.Upgrade(c.Writer, c.Request)
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index cb1ac4b53d..538343b701 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -1688,7 +1688,7 @@ func serveWebSocket(ginServer *gin.Engine) {
util.WebSocketServer = melody.New()
// 校验 Origin,防止跨站 WebSocket 劫持(CSWSH) https://github.com/siyuan-note/siyuan/security/advisories/GHSA-3cc2-h3v6-rqpq
util.WebSocketServer.Upgrader.CheckOrigin = func(r *http.Request) bool {
- return util.IsSessionOriginAllowed(r.Header.Get("Origin"), r.Host)
+ return util.IsSessionOriginAllowedRequest(r)
}
util.WebSocketServer.Config.MaxMessageSize = 1024 * 1024 * 8
diff --git a/kernel/util/net.go b/kernel/util/net.go
index 29f276af5a..8feeedba85 100644
--- a/kernel/util/net.go
+++ b/kernel/util/net.go
@@ -138,6 +138,25 @@ func IsSessionOriginAllowed(origin, host string) bool {
return originHostEquals(origin, host)
}
+// IsCrossSiteFetchSite 根据 Sec-Fetch-Site 请求头判断是否为浏览器发起的跨站请求。
+// 浏览器为所有请求携带 Sec-Fetch-Site,取值 same-origin(同源)、same-site(同站跨源)、
+// cross-site(跨站)、none(用户直接输入地址等);跨站顶层 GET 导航不携带 Origin,
+// 仅凭 Origin 无法识别,因此需要结合该请求头判断。未携带时视为非浏览器客户端。
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743
+func IsCrossSiteFetchSite(site string) bool {
+ return "" != site && "same-origin" != site && "none" != site
+}
+
+// IsSessionOriginAllowedRequest 校验会话认证请求是否允许放行:浏览器标记的跨站请求直接拒绝,
+// 其余请求继续校验 Origin。
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743
+func IsSessionOriginAllowedRequest(r *http.Request) bool {
+ if IsCrossSiteFetchSite(r.Header.Get("Sec-Fetch-Site")) {
+ return false
+ }
+ return IsSessionOriginAllowed(r.Header.Get("Origin"), r.Host)
+}
+
func originHostEquals(origin, host string) bool {
u, err := url.Parse(origin)
if nil != err {
diff --git a/kernel/util/net_test.go b/kernel/util/net_test.go
index 4b5a3cdcb6..05094b6e6a 100644
--- a/kernel/util/net_test.go
+++ b/kernel/util/net_test.go
@@ -19,6 +19,8 @@ package util
import (
"context"
"net"
+ "net/http"
+ "net/http/httptest"
"testing"
"time"
)
@@ -54,6 +56,63 @@ func TestIsSessionOriginAllowed(t *testing.T) {
}
}
+// TestIsCrossSiteFetchSite 验证 Sec-Fetch-Site 请求头的跨站判断逻辑
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743
+func TestIsCrossSiteFetchSite(t *testing.T) {
+ tests := []struct {
+ name string
+ site string
+ want bool
+ }{
+ {name: "absent header", site: "", want: false},
+ {name: "same-origin", site: "same-origin", want: false},
+ {name: "none", site: "none", want: false},
+ {name: "same-site", site: "same-site", want: true},
+ {name: "cross-site", site: "cross-site", want: true},
+ {name: "unknown value", site: "unknown", want: true},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ if got := IsCrossSiteFetchSite(test.site); got != test.want {
+ t.Fatalf("IsCrossSiteFetchSite(%q) = %v, want %v", test.site, got, test.want)
+ }
+ })
+ }
+}
+
+// TestIsSessionOriginAllowedRequest 验证会话认证请求校验:浏览器标记的跨站请求直接拒绝,
+// 其余请求回退到 Origin 校验
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743
+func TestIsSessionOriginAllowedRequest(t *testing.T) {
+ tests := []struct {
+ name string
+ site string
+ origin string
+ host string
+ want bool
+ }{
+ {name: "cross-site navigation without Origin", site: "cross-site", origin: "", host: "127.0.0.1:6806", want: false},
+ {name: "same-site without Origin", site: "same-site", origin: "", host: "127.0.0.1:6806", want: false},
+ {name: "same-origin without Origin", site: "same-origin", origin: "", host: "127.0.0.1:6806", want: true},
+ {name: "none without Origin", site: "none", origin: "", host: "127.0.0.1:6806", want: true},
+ {name: "absent fetch site with local origin", site: "", origin: "http://127.0.0.1:6806", host: "127.0.0.1:6806", want: true},
+ {name: "absent fetch site with cross-site origin", site: "", origin: "https://evil.example", host: "127.0.0.1:6806", want: false},
+ {name: "cross-site with matching origin", site: "cross-site", origin: "http://127.0.0.1:6806", host: "127.0.0.1:6806", want: false},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ request := httptest.NewRequest(http.MethodGet, "http://"+test.host+"/", nil)
+ request.Header.Set("Sec-Fetch-Site", test.site)
+ request.Header.Set("Origin", test.origin)
+ if got := IsSessionOriginAllowedRequest(request); got != test.want {
+ t.Fatalf("IsSessionOriginAllowedRequest(site=%q, origin=%q, host=%q) = %v, want %v", test.site, test.origin, test.host, got, test.want)
+ }
+ })
+ }
+}
+
// TestIsPrivateIP 验证 isPrivateIP 对私网地址及 IPv6 过渡地址的判断
// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-qq8m-8p8v-x4xg
// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-rg26-cg95-gq6p