[LOW] SQL LIKE 查询未转义通配符:用户输入可导致全表扫描/数据泄露 #14

Closed
opened 2026-04-30 03:56:58 +08:00 by lan · 0 comments
Owner

问题描述

多处搜索功能使用 LIKE 查询时,直接将用户输入拼接到搜索模式中,未转义 %_ 通配符。

影响位置

  • internal/repository/material_repo.go:97, 201 — 材料搜索
  • internal/repository/verification_repo.go:73 — 实名认证搜索
  • internal/repository/post_repo.go:514, 881, 1129 — 帖子搜索
// material_repo.go:97
query = query.Where("title LIKE ? OR description LIKE ?", keyword, keyword)
// 若 keyword = "%%%" 或 "%_%_" 可匹配大量记录

风险

  1. 性能攻击:用户输入 % 作为搜索关键词,导致全表扫描,消耗数据库资源
  2. 信息泄露:通过 _ 通配符逐个字符试探,可能推断出数据库中的敏感数据
  3. 拒绝服务:多次发送通配符搜索请求可耗尽数据库连接池

修复建议

import "strings"

// 转义 LIKE 通配符
keyword = strings.NewReplacer(
    "%", `\%`,
    "_", `\_`,
).Replace(keyword)

query = query.Where("title LIKE ? OR description LIKE ?", 
    "%"+keyword+"%", "%"+keyword+"%")

或在 SQL 中使用 ESCAPE 子句:

WHERE title LIKE ? ESCAPE '\'

严重程度

LOW — 非直接安全漏洞,但可被用于 DoS 和数据推断。

## 问题描述 多处搜索功能使用 `LIKE` 查询时,直接将用户输入拼接到搜索模式中,未转义 `%` 和 `_` 通配符。 ### 影响位置 - `internal/repository/material_repo.go:97, 201` — 材料搜索 - `internal/repository/verification_repo.go:73` — 实名认证搜索 - `internal/repository/post_repo.go:514, 881, 1129` — 帖子搜索 ```go // material_repo.go:97 query = query.Where("title LIKE ? OR description LIKE ?", keyword, keyword) // 若 keyword = "%%%" 或 "%_%_" 可匹配大量记录 ``` ## 风险 1. **性能攻击**:用户输入 `%` 作为搜索关键词,导致全表扫描,消耗数据库资源 2. **信息泄露**:通过 `_` 通配符逐个字符试探,可能推断出数据库中的敏感数据 3. **拒绝服务**:多次发送通配符搜索请求可耗尽数据库连接池 ## 修复建议 ```go import "strings" // 转义 LIKE 通配符 keyword = strings.NewReplacer( "%", `\%`, "_", `\_`, ).Replace(keyword) query = query.Where("title LIKE ? OR description LIKE ?", "%"+keyword+"%", "%"+keyword+"%") ``` 或在 SQL 中使用 `ESCAPE` 子句: ```sql WHERE title LIKE ? ESCAPE '\' ``` ## 严重程度 **LOW** — 非直接安全漏洞,但可被用于 DoS 和数据推断。
lan closed this issue 2026-04-30 12:23:20 +08:00
Sign in to join this conversation.
No Label
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: carrot_bbs/backend#14