Skip to content

fix: 防止菜单名路径穿透写入/删除资源目录外的文件 - #45

Merged
Cvandia merged 1 commit into
Cvandia:mainfrom
SuellenQwQ:fix/path-traversal-in-menu
Oct 21, 2026
Merged

Cvandia merged 1 commit into
Cvandia:mainfrom
SuellenQwQ:fix/path-traversal-in-menu

Conversation

@SuellenQwQ

Copy link
Copy Markdown

问题

添加/删除菜单时,菜品名 name 未做任何校验就被拼进文件路径:

save_path = Path(config.whatpic_res_path) / f"{img_type}_pic" / (name + ".jpg")

构造 ../../xxx 这样的名字即可逃出资源目录,写入任意位置;delete_pic 同理,可删除资源目录外的 .jpg。失败时抛出的 FileNotFoundError 还会把 nonebot 的完整运行路径回显给用户。

复现

添加菜单
红烧肉/../../escaped      # 图片被写到资源目录之外

资源目录设为 <tmp>/res 时,该操作会在 <tmp>/escaped.jpg 落盘(已在本地对照验证,修复前成功写出文件,修复后被拦截)。

变更

  • 新增 resolve_pic_path(),统一解析菜品图片路径:
    • img_type 仅允许 eat / drink
    • 拒绝含路径分隔符、空字节的名字,以及 . / ..
    • resolve() 后二次校验结果仍在资源目录内,避免绕过字符检查
  • save_pic() / delete_pic() 改用 resolve_pic_path()
  • save_pic() 的 bytes 类型检查提到写文件之前(原来失败时会先创建空文件)
  • matcher 捕获 ValueError,向用户返回「菜名不合法」而不是未处理异常

测试

新增 tests/test_files.py(16 项,本地全通过):

  • 正常菜名解析到资源目录内
  • 10 种恶意名字被拒绝(../、..\\、a/b、绝对路径、空字节等)
  • 非法 img_type 被拒绝
  • 断言攻击不会在资源目录外产生文件

ruff check nonebot_plugin_whateat_pic/ tests/ 通过。

Refs #43

在添加或删除菜单时, 菜品名会被直接拼进文件路径, 未做任何校验。
构造 `../../xxx` 这样的名字即可把文件写到资源目录之外,
或者删除目录外的任意 .jpg 文件; 报错信息还会暴露 nonebot 的运行路径。

Changes:
- 新增 resolve_pic_path(), 统一解析菜品图片路径
  - 校验 img_type 仅允许 eat / drink
  - 拒绝含路径分隔符、空字节、`.` / `..` 的名字
  - resolve() 后二次校验路径仍在资源目录内, 防止绕过字符检查
- save_pic() / delete_pic() 改用 resolve_pic_path()
  - save_pic 的 bytes 类型检查提到写文件之前
- matcher 捕获 ValueError, 向用户返回“菜名不合法”而不是抛未处理异常

Tests:
- tests/test_files.py 覆盖正常名字、10 种恶意名字、非法 img_type,
  并断言不会在资源目录外产生文件
- ruff check 通过

Refs Cvandia#43
@deepsource-io

deepsource-io Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

DeepSource Code Review

We reviewed changes in df38a4f...99486a4 on this pull request. Below is the summary for the review, and you can see the individual issues we found as inline review comments.

See full review on DeepSource ↗

PR Report Card

Overall Grade   Security  

Reliability  

Complexity  

Hygiene  

Code Review Summary

Analyzer Status Updated (UTC) Details
Python Sep 16, 2026 12:23p.m. Review ↗

Important

AI Review is run only on demand for your team. We're only showing results of static analysis review right now. To trigger AI Review, comment @deepsourcebot review on this thread.

@Cvandia
Cvandia merged commit 0d88418 into Cvandia:main Oct 21, 2026
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants