Skip to content

fix(net/ghttp): anchor static file reads to the search root - #4985

Merged
hailaz merged 7 commits into
gogf:masterfrom
LanceAdd:fix/ghttp-static-root
Nov 23, 2026
Merged

hailaz merged 7 commits into
gogf:masterfrom
LanceAdd:fix/ghttp-static-root

Conversation

@LanceAdd

Copy link
Copy Markdown
Member

背景

ghttp 磁盘静态文件的越界校验只依赖 gspath.Search 里的路径前缀检查。这个检查挡不住两类情况:

  • 结果路径与搜索根共享字符串前缀的兄弟目录,例如根 /srv/static 与目录 /srv/static-evil;
  • 搜索根内指向根外的符号链接,Stat/Open 会跟随链接,而路径串仍停在根内。

两者都会把配置根之外的文件当作静态资源返回,属于越权读取:兄弟目录只暴露同前缀的相邻路径,符号链接则可读取进程有权限的任意文件。触发前提是启用了静态文件服务(SetServerRoot / AddSearchPath / AddStaticPath),且请求路径未被客户端规范化(curl --path-as-is、原始 socket、%2e%2e 编码均可)。

复现

以 static 为静态根,布局如下:

static/inside.txt                inside
static/escape-relative.txt  ->   ../outside/secret.txt
static/escape-absolute.txt  ->   <绝对路径>/outside/secret.txt
static-evil/secret.txt           sibling-secret
outside/secret.txt               symlink-secret

SetServerRoot(<root>/static) 启动服务后,直接发送未规范化的请求:

curl --path-as-is "http://127.0.0.1:<port>/../static-evil/secret.txt"
curl "http://127.0.0.1:<port>/escape-relative.txt"
curl "http://127.0.0.1:<port>/escape-absolute.txt"

改动前三个请求分别返回 sibling-secret、symlink-secret、symlink-secret;改动后均返回 403,/inside.txt 仍返回 inside。自动化版本见 Test_Static_ServerRoot_Security_Escape。

改动

  • staticFile 增加 RootPath,searchStaticFile 为 StaticPaths、SearchPaths 搜索到的磁盘文件记录对应搜索根;
  • serveFile 打开磁盘文件时先计算 filepath.Rel,用 filepath.IsLocal 过滤越界结果,再通过 os.OpenRoot(RootPath).Open(rel) 打开;
  • 最终由 os.Root 在打开时按目录句柄和平台语义校验,覆盖 ..、绝对路径和逃逸符号链接;
  • Response.ServeFile、ServeFileDownload 是显式路径 API,不经过该流程,行为不变。

兼容性

  • 合法路径的解析与返回内容不变;根内、目标在根内的相对符号链接仍可访问。
  • 指向根外的符号链接(相对或绝对)与绝对符号链接本身会被 os.Root 拒绝,即使其目标落在根内——这是 os.Root 的既定约束,需要按符号链接对外提供根外目录的部署不再适用。
  • 越界文件仍返回原有的 403,错误文本与日志未改。
  • 无导出 API 变更;gres 内存资源不涉及磁盘打开,行为不变。
  • 越界判定不再依赖字符串前缀,Windows 下同样由 os.Root 拒绝逃逸路径。

测试

  • go test ./net/ghttp/ -run 'Test_Static' -count=1
  • 新增 Test_Static_ServerRoot_Security_Escape:
    • 兄弟目录前缀(/../static-evil/secret.txt)不返回根外内容;
    • 根内指向根外的符号链接不返回根外内容;
    • 根内普通文件与根内符号链接正常返回。
  • 该用例在修复前失败(三种请求均返回根外内容),修复后通过。
  • 符号链接用例在不支持创建链接的平台上跳过。
  • gofmt 干净。

改动文件

net/ghttp/ghttp_request.go                       staticFile 增加 RootPath
net/ghttp/ghttp_server_handler.go                静态文件记录根并经 os.Root 打开
net/ghttp/ghttp_z_unit_feature_static_test.go    新增:逃逸用例

提交

5049433af fix(net/ghttp): anchor static file reads to the search root

Disk files found by searchStaticFile now record their search root and
are opened through os.Root, so paths escaping the root are rejected at
open time.

This closes two escapes the previous path-prefix check missed: a sibling
directory sharing the root string prefix, and a symbolic link inside the
root pointing outside. Both are covered by a test that fails before this
change.

Response.ServeFile and ServeFileDownload are explicit-path APIs and keep
opening paths as given.
@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 85.08%. Comparing base (9258ee8) to head (8be75dc).

Files with missing lines Patch % Lines
net/ghttp/ghttp_server_handler.go 96.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4985      +/-   ##
==========================================
+ Coverage   85.02%   85.08%   +0.05%     
==========================================
  Files         893      893              
  Lines       47167    47187      +20     
==========================================
+ Hits        40103    40148      +45     
+ Misses       7064     7039      -25     
Flag Coverage Δ
go-1.27-core 72.78% <96.00%> (+0.02%) ⬆️
go-1.27-drivers-1 27.57% <0.00%> (-0.02%) ⬇️
go-1.27-drivers-2 27.38% <0.00%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@gqcn

gqcn commented Nov 19, 2026

Copy link
Copy Markdown
Member

这次改动整体方向可以继续推进,通过 os.Root 锚定磁盘静态文件读取能有效拦截同前缀兄弟目录和外部符号链接逃逸,不过还有几处建议先完善后再合并:

  • 建议优先处理 net/ghttp/ghttp_server_handler.go:338:openStaticFile 直接使用 f.RootPath 与 f.Path 计算 filepath.Rel,当通过 ServerConfig.SearchPaths 配置相对路径(SetConfig 中 s.config.SearchPaths 仍保留了原始相对路径项)或目录名命中 gres 跳过绝对路径转换时,f.RootPath 为相对路径而 gspath.Search 返回的 f.Path 为绝对路径,会使 filepath.Rel 报错并将合法静态文件误判为 403。可以考虑在 openStaticFile 中先用 filepath.Abs 对 f.RootPath 做归一化,再计算 filepath.Rel 并调用 os.OpenRoot。
  • 建议完善 net/ghttp/ghttp_server_handler.go:354:defer 中使用 _ = root.Close() 丢弃了关闭目录句柄的错误返回值。建议显式处理该错误,例如参考同文件 handleAfterRequestDone 的写法通过 intlog.Errorf 记录异常日志。
  • 建议完善 net/ghttp/ghttp_z_unit_feature_static_test.go:102-103:新增的 Test_Static_ServerRoot_Security_Escape 中调用 s.Start() 和 defer s.Shutdown() 时忽略了返回的 error。如果可能的话,建议一并使用 t.AssertNil 校验这两处的错误返回值。

我暂时没有添加bot-approved标签。

Normalize the search root and file path with filepath.Abs before
computing the relative path for os.OpenRoot, so relative SearchPaths and
StaticPaths keep serving files instead of returning 403.

Log root close errors and assert server start/shutdown errors in the new
static security test.
@LanceAdd

Copy link
Copy Markdown
Member Author

三点已处理,最新 head d9a052fb4:

  • openStaticFile 先对 f.RootPath 和 f.Path 做 filepath.Abs,再计算 filepath.Rel、filepath.IsLocal,并用 os.OpenRoot(rootPath) 打开;新增 Test_Static_RelativeSearchPath,用相对 SearchPaths 验证合法静态文件不再被误判为 403。
  • root.Close() 的错误改为通过 intlog.Errorf 记录。
  • 新用例的 s.Start() / s.Shutdown() 已改为 t.AssertNil 校验。

验证:go test ./net/ghttp -run "^Test_Static" -count=1、go vet ./net/ghttp 通过。

Use gfile.Abs for the root and file paths, dropping the filepath.Abs
error branches that cannot fail here, and report a Rel failure as an
outside-root path. Add an internal test for a missing root so the
OpenRoot error is covered.
@LanceAdd

Copy link
Copy Markdown
Member Author

补一条最新 head 0e443383b 的说明(上一条对应 d9a052fb4):

  • 路径归一化由 filepath.Abs 改为仓库已有的 gfile.Abs(内部即 filepath.Abs):Abs 只在“相对路径 + Getwd 失败”时报错,这两个错误分支测试无法触发,导致 codecov/patch 卡在 83.87%;
  • filepath.Rel 失败并入 !filepath.IsLocal(relPath) 判断,统一按越界处理,对外仍是 403;
  • 新增内部单测 Test_OpenStaticFile_MissingRoot,覆盖 os.OpenRoot 失败分支;
  • root.Close() 的 intlog.Errorf、s.Start() / s.Shutdown() 的 t.AssertNil 均保持不变。

验证:go test ./net/ghttp -run '^(Test_Static|Test_OpenStaticFile)' -count=1、gofmt 通过。

@gqcn

gqcn commented Nov 23, 2026

Copy link
Copy Markdown
Member

之前提到的几处已经在当前 head 8be75dc 里对上了。

openStaticFile 会先用 gfile.Abs 把搜索根和文件路径转成绝对路径,再计算 filepath.Rel,并用 os.OpenRoot 打开。相对 SearchPaths 下的合法文件不会再被当成越界返回 403,Test_Static_RelativeSearchPath 覆盖了这条路径。关闭 root 失败时会记到 intlog,新用例里的 Start 和 Shutdown 也会检查返回的错误。

当前 head 的检查是通过的。这次是把磁盘静态文件限制在对应搜索根里:同前缀的兄弟目录,以及指向根外的符号链接,都会在打开时被拒绝。

@gqcn gqcn added the bot-approved Approved by gf-pr-review label Nov 23, 2026
@hailaz
hailaz merged commit 8e128e2 into gogf:master Nov 23, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-approved Approved by gf-pr-review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants