Skip to content

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

:lock: Prevent stored XSS via inline rendering of script-capable assets https://github.com/siyuan-note/siyuan/security/advisories/GHSA-mjf3-jwmf-r6wf

Daniel8e85058a383f
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index b9ab879e3d..ed9bb5db69 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -831,6 +831,34 @@ func setAssetsAttachmentDisposition(c *gin.Context, pathForBaseName string) {
c.Header("Content-Disposition", formatContentDispositionAttachment(filepath.Base(pathForBaseName)))
}
+// assetScriptCapableExts 为可执行脚本的资产扩展名,禁止浏览器内联渲染,必须强制以附件形式返回
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-mjf3-jwmf-r6wf
+var assetScriptCapableExts = map[string]bool{
+ ".cjs": true, ".htm": true, ".html": true, ".js": true, ".mjs": true,
+ ".shtml": true, ".svg": true, ".xhtml": true, ".xml": true,
+}
+
+// isAssetInlineUnsafe 判断资产是否禁止浏览器内联渲染:
+// 可执行脚本的扩展名,或标准库无法识别 Content-Type 的扩展名(http.ServeFile 会内容嗅探,可能识别为 text/html 执行脚本)
+func isAssetInlineUnsafe(absPath string) bool {
+ ext := strings.ToLower(filepath.Ext(absPath))
+ if assetScriptCapableExts[ext] {
+ return true
+ }
+ return mime.TypeByExtension(ext) == ""
+}
+
+// secureAssetContentHeaders 统一为资产响应设置安全头:
+// 无条件加 X-Content-Type-Options: nosniff,可执行脚本的类型无条件强制附件下载;
+// absPath 用于判断内容类型,dispositionName 用于 Content-Disposition 文件名(加密笔记本场景为原始文件名)
+func secureAssetContentHeaders(context *gin.Context, absPath, dispositionName string) {
+ setAssetsAttachmentDisposition(context, dispositionName)
+ context.Header("X-Content-Type-Options", "nosniff")
+ if isAssetInlineUnsafe(absPath) {
+ context.Header("Content-Disposition", formatContentDispositionAttachment(filepath.Base(dispositionName)))
+ }
+}
+
func isValidAssetRequestPath(requestPath string) bool {
relativePath := strings.TrimPrefix(requestPath, "/")
if relativePath == "" || relativePath == "." {
@@ -921,7 +949,7 @@ func serveAssets(ginServer *gin.Engine) {
}
// 返回原始文件
- setAssetsAttachmentDisposition(context, p)
+ secureAssetContentHeaders(context, p, p)
http.ServeFile(context.Writer, context.Request, p)
})
@@ -931,6 +959,7 @@ func serveAssets(ginServer *gin.Engine) {
if serveEncryptedHistory(context, p) {
return
}
+ secureAssetContentHeaders(context, p, p)
http.ServeFile(context.Writer, context.Request, p)
})
}
@@ -1036,11 +1065,11 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {
return true
}
// 下载时用原始文件名(查加密映射),查不到则退回磁盘名
+ dispositionName := absPath
if originalName := model.LookupAssetOriginalNameLocked(boxID, diskName); originalName != "" {
- setAssetsAttachmentDisposition(context, originalName)
- } else {
- setAssetsAttachmentDisposition(context, absPath)
+ dispositionName = originalName
}
+ secureAssetContentHeaders(context, absPath, dispositionName)
contentType := mime.TypeByExtension(filepath.Ext(absPath))
if contentType == "" {
contentType = "application/octet-stream"
@@ -1119,6 +1148,7 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
context.Status(http.StatusInternalServerError)
return true
}
+ secureAssetContentHeaders(context, absPath, absPath)
contentType := mime.TypeByExtension(filepath.Ext(absPath))
if contentType == "" {
contentType = "application/octet-stream"
@@ -1161,7 +1191,7 @@ func serveThumbnail(context *gin.Context, assetAbsPath, requestPath string) bool
}
}
- setAssetsAttachmentDisposition(context, assetAbsPath)
+ secureAssetContentHeaders(context, assetAbsPath, assetAbsPath)
http.ServeFile(context.Writer, context.Request, thumbnailPath)
return true
}
diff --git a/kernel/server/serve_assets_test.go b/kernel/server/serve_assets_test.go
index 1131de93a4..809b26cc3f 100644
--- a/kernel/server/serve_assets_test.go
+++ b/kernel/server/serve_assets_test.go
@@ -5,21 +5,17 @@
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU Affero General Public License for more details.
-//
-// You should have received a copy of the GNU Affero General Public License
-// along with this program. If not, see <https://www.gnu.org/licenses/>.
package server
import (
+ "mime"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"runtime"
+ "strings"
"testing"
"github.com/gin-gonic/gin"
@@ -93,3 +89,87 @@ func TestAssetRequestPathURLDecoding(t *testing.T) {
})
}
}
+
+func TestSecureAssetContentHeadersForcesAttachmentOnScriptCapableAssets(t *testing.T) {
+ // 可执行脚本的资产必须强制附件下载,禁止浏览器同源内联渲染
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-mjf3-jwmf-r6wf
+ cases := map[string]string{
+ "test.html": "<script>fetch('/api/system/getConf')</script>",
+ "test.xhtml": "<script>fetch('/api/system/getConf')</script>",
+ "test.js": "fetch('/api/system/getConf')",
+ "test.svg": "<svg xmlns='http://www.w3.org/2000/svg'><script>fetch('/api/system/getConf')</script></svg>",
+ }
+ for name, content := range cases {
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodGet, "/assets/"+name, nil)
+ assetPath := filepath.Join(t.TempDir(), name)
+ if err := os.WriteFile(assetPath, []byte(content), 0644); err != nil {
+ t.Fatalf("write test asset failed: %v", err)
+ }
+ secureAssetContentHeaders(context, assetPath, assetPath)
+ if !strings.HasPrefix(recorder.Header().Get("Content-Disposition"), "attachment") {
+ t.Fatalf("asset [%s] must be forced to download, got Content-Disposition %q", name, recorder.Header().Get("Content-Disposition"))
+ }
+ if recorder.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatalf("asset [%s] missing X-Content-Type-Options header", name)
+ }
+ }
+}
+
+func TestSecureAssetContentHeadersAllowsInlineSafeAssets(t *testing.T) {
+ // 图片、音视频、PDF 等安全类型保持内联渲染,但仍需 nosniff
+ cases := []string{"test.png", "test.jpg", "test.webp", "test.mp4", "test.mp3", "test.pdf", "test.txt"}
+ for _, name := range cases {
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodGet, "/assets/"+name, nil)
+ assetPath := filepath.Join(t.TempDir(), name)
+ if err := os.WriteFile(assetPath, []byte("test"), 0644); err != nil {
+ t.Fatalf("write test asset failed: %v", err)
+ }
+ secureAssetContentHeaders(context, assetPath, assetPath)
+ if cd := recorder.Header().Get("Content-Disposition"); strings.HasPrefix(cd, "attachment") {
+ t.Fatalf("safe asset [%s] must stay inline, got Content-Disposition %q", name, cd)
+ }
+ if recorder.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatalf("safe asset [%s] missing X-Content-Type-Options header", name)
+ }
+ }
+}
+
+func TestSecureAssetContentHeadersForcesAttachmentOnUnknownExtension(t *testing.T) {
+ // 无法识别 Content-Type 的扩展名会触发内容嗅探,可能被识别为 text/html,因此必须强制附件下载
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodGet, "/assets/payload.xyz", nil)
+ assetPath := filepath.Join(t.TempDir(), "payload.xyz")
+ if err := os.WriteFile(assetPath, []byte("<script>alert(1)</script>"), 0644); err != nil {
+ t.Fatalf("write test asset failed: %v", err)
+ }
+ if mime.TypeByExtension(".xyz") != "" {
+ t.Fatalf("test precondition failed: .xyz unexpectedly has a MIME type")
+ }
+ secureAssetContentHeaders(context, assetPath, assetPath)
+ if !strings.HasPrefix(recorder.Header().Get("Content-Disposition"), "attachment") {
+ t.Fatalf("unknown-extension asset must be forced to download, got Content-Disposition %q", recorder.Header().Get("Content-Disposition"))
+ }
+ if recorder.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatalf("unknown-extension asset missing X-Content-Type-Options header")
+ }
+}
+
+func TestSecureAssetContentHeadersKeepsExplicitDownload(t *testing.T) {
+ // 显式携带 download=true 时安全类型也应返回 attachment
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodGet, "/assets/test.png?download=true", nil)
+ assetPath := filepath.Join(t.TempDir(), "test.png")
+ if err := os.WriteFile(assetPath, []byte("png"), 0644); err != nil {
+ t.Fatalf("write test asset failed: %v", err)
+ }
+ secureAssetContentHeaders(context, assetPath, assetPath)
+ if !strings.HasPrefix(recorder.Header().Get("Content-Disposition"), "attachment") {
+ t.Fatalf("explicit download=true must return attachment, got Content-Disposition %q", recorder.Header().Get("Content-Disposition"))
+ }
+}