安全审计与加固:爱发电回调防投毒、回调日志封顶、令牌定长比较、转义补全;nginx 安全头 / 挡备份与原始内容文件(片段 + 文档)

Browse Source
- 没验证过的爱发电回调不再写进账本 pay_orders,只进 50 条封顶的待核对清单;回调日志只记关键头 + 正文 4KB、5MB 轮转(测试 +2)
- 福利券领取令牌定长比较;ys_admin.py 转义补上引号;星门格子提示转义;首页价格改读公开接口
- nginx 片段:安全头(HSTS/nosniff/XFO/Referrer/Permissions/CSP)、挡备份 / 预览稿 / 隐藏文件 / 原始内容 json、回调单独限流、server_tokens off
- 交接文档 2.9 安全加固 + 维护页挂法更新

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yws
2026-10-06 12:52:16 +00:00
co-authored by Claude Opus 5.5
parent 9f2322e7ae
commit cb7cd3649b
13 changed files with 133 additions and 53 deletions
+29 -13
View File
@@ -60,6 +60,19 @@ def payplatform_api(path, params=None):
return {"ec": -1, "em": "调用失败:%r" % e} return {"ec": -1, "em": "调用失败:%r" % e}
def _hook_unverified(oid_af, order, why, ip):
"""没验证过的爱发电回调:只留最近 50 条在 kv「hook_unverified」里,给金钻人工核对用(2026-10-06 安全加固)。
字段全部截断,不进账本 pay_orders —— 伪造的报文刷再多也只占这 50 格。"""
try:
lst = STORE.kv_get("hook_unverified", []) or []
lst.append({"ts": now().isoformat(timespec="seconds"), "out_trade_no": str(oid_af)[:64], "why": why[:60],
"amount": str(order.get("show_amount") or order.get("total_amount") or "")[:16],
"title": ("%s %s" % (order.get("plan_title") or "", order.get("title") or "")).strip()[:60], "ip": str(ip)[:45]})
STORE.kv_put("hook_unverified", lst[-50:])
except Exception as e:
log("记待核对回调失败:%s" % e)
def payplatform_find_order(out_trade_no, pages=3): def payplatform_find_order(out_trade_no, pages=3):
"""按订单号反查(确认这笔真的存在、真的付款了)。返回订单 dict 或 None。""" """按订单号反查(确认这笔真的存在、真的付款了)。返回订单 dict 或 None。"""
for pg in range(1, pages + 1): for pg in range(1, pages + 1):
@@ -401,7 +414,8 @@ def gift_claim(bid, token, ip):
return False, "这批券过期了" return False, "这批券过期了"
with LOCK: with LOCK:
cs = load_codes() cs = load_codes()
mine = [c for c, r in cs.items() if r.get("gift") == bid and r.get("claim_token") == tok] mine = [c for c, r in cs.items() if r.get("gift") == bid and isinstance(tok, str) and tok
and hmac.compare_digest(str(r.get("claim_token") or ""), tok)] # 定长比较(2026-10-06 安全加固)
if mine: if mine:
return False, "你已经领过啦 —— 这批每人限一张 😉 想多要就等下一波福利" return False, "你已经领过啦 —— 这批每人限一张 😉 想多要就等下一波福利"
ip_n = len([c for c, r in cs.items() ip_n = len([c for c, r in cs.items()
@@ -2266,10 +2280,16 @@ class H(BaseHTTPRequestHandler):
obj = json.loads(raw.decode("utf-8", "replace") or "{}") obj = json.loads(raw.decode("utf-8", "replace") or "{}")
except ValueError: except ValueError:
obj = {"_parse_error": True, "_raw": raw[:2000].decode("utf-8", "replace")} obj = {"_parse_error": True, "_raw": raw[:2000].decode("utf-8", "replace")}
# 回调日志(2026-10-06 安全加固):这个地址谁都能 POST —— 只记几个关键头 + 正文前 4KB,
# 超过 5MB 轮转成 .1(只留一份旧的),不然一个人就能把磁盘写满。
try: try:
if os.path.exists(PAYPLATFORM_LOG) and os.path.getsize(PAYPLATFORM_LOG) > 5 * 1024 * 1024:
os.replace(PAYPLATFORM_LOG, PAYPLATFORM_LOG + ".1")
keep = {k: v for k, v in self.headers.items() if k.lower() in ("user-agent", "content-type", "x-real-ip", "x-forwarded-for")}
body = json.dumps(obj, ensure_ascii=False)
with open(PAYPLATFORM_LOG, "a", encoding="utf-8") as f: with open(PAYPLATFORM_LOG, "a", encoding="utf-8") as f:
f.write(json.dumps({"ts": now().isoformat(timespec="seconds"), "ip": ip_of(self), f.write(json.dumps({"ts": now().isoformat(timespec="seconds"), "ip": ip_of(self), "headers": keep,
"headers": dict(self.headers.items()), "body": obj}, "body": body[:4096] + ("…(截断)" if len(body) > 4096 else "")},
ensure_ascii=False) + "\n") ensure_ascii=False) + "\n")
except OSError: except OSError:
pass pass
@@ -2300,21 +2320,17 @@ class H(BaseHTTPRequestHandler):
if int(order.get("status") or 0) != 2: if int(order.get("status") or 0) != 2:
log("爱发电回调:%s 状态不是已付款(status=%s),先不发码" log("爱发电回调:%s 状态不是已付款(status=%s),先不发码"
% (oid_af, order.get("status"))) % (oid_af[:64], str(order.get("status"))[:8]))
led[oid_af] = {"ts": now().isoformat(timespec="seconds"), "status": order.get("status"), # ⚠️ 2026-10-06 安全加固:没经过开放接口验证的报文**不写进账本**(原来会把任何人编的单号 / 金额
"amount": order.get("show_amount") or order.get("total_amount"), # 写进库里的 pay_orders,一刷就是成千上万条,每次存账本还要整表重写 → 拖慢真付款)。
"code": None, "note": "未付款"} _hook_unverified(oid_af, order, "未付款(status=%s)" % str(order.get("status"))[:8], ip_of(self))
STORE.ledger_save(led)
return self.js({"ec": 200, "em": ""}) return self.js({"ec": 200, "em": ""})
real = payplatform_find_order(oid_af) real = payplatform_find_order(oid_af)
if not real: if not real:
# 没验过就不发码 —— 宁可让金钻手工补,也不给伪造的报文发货 # 没验过就不发码 —— 宁可让金钻手工补,也不给伪造的报文发货
log("⚠️ 爱发电回调:%s 在开放接口里查不到(可能官方延迟/伪造),没发码" % oid_af) log("⚠️ 爱发电回调:%s 在开放接口里查不到(可能官方延迟/伪造),没发码" % oid_af[:64])
led[oid_af] = {"ts": now().isoformat(timespec="seconds"), "code": None, _hook_unverified(oid_af, order, "接口没查到,待人工核对", ip_of(self))
"amount": order.get("show_amount") or order.get("total_amount"),
"note": "接口没查到,待人工核对", "need_human": True}
STORE.ledger_save(led)
return self.js({"ec": 200, "em": ""}) return self.js({"ec": 200, "em": ""})
n_img_af = payplatform_img_count(real) n_img_af = payplatform_img_count(real)
@@ -199,6 +199,22 @@ m2 = S.read_meta(h2)
check("洞:同一笔付款改报文里的订单号,不能再激活另一单", (m2 or {}).get("state") in ("unpaid", "paid"), check("洞:同一笔付款改报文里的订单号,不能再激活另一单", (m2 or {}).get("state") in ("unpaid", "paid"),
"第二单状态=%s" % (m2 or {}).get("state")) "第二单状态=%s" % (m2 or {}).get("state"))
# 2026-10-06 安全加固:伪造的回调(没付款 / 开放接口查不到)不能写进账本,刷再多也只占 50 格待核对
led0 = len(S.STORE.ledger_all())
for k in range(60):
fake = {"data": {"order": {"out_trade_no": "FAKE%04d" % k, "status": 1 if k % 2 else 2,
"total_amount": "999", "title": "x" * 500}}}
req("POST", "/api/payplatform-hook", fake)
pend = S.STORE.kv_get("hook_unverified", []) or []
check("洞:伪造回调刷 60 次 → 账本一条都不多,待核对清单封顶 50 条、字段截断",
len(S.STORE.ledger_all()) == led0 and len(pend) == 50 and all(len(x.get("title", "")) <= 60 for x in pend),
"账本 %d → %d,待核对 %d 条" % (led0, len(S.STORE.ledger_all()), len(pend)))
logsz = os.path.getsize(S.PAYPLATFORM_LOG) if os.path.exists(S.PAYPLATFORM_LOG) else 0
hook_big = {"data": {"order": {"out_trade_no": "BIG", "status": 1}}, "junk": "y" * 60000}
req("POST", "/api/payplatform-hook", hook_big)
grew = (os.path.getsize(S.PAYPLATFORM_LOG) if os.path.exists(S.PAYPLATFORM_LOG) else 0) - logsz
check("加固:回调日志一条最多记 4KB 正文(60KB 的报文不会整包写盘)", 0 < grew < 6000, "这一条写了 %d 字节" % grew)
# ================================================================== 5. 重渲换皮肤绕过 PNG 核验 # ================================================================== 5. 重渲换皮肤绕过 PNG 核验
st, j, _ = submit([S.gen_codes(1)[0]], ["stand"]) st, j, _ = submit([S.gen_codes(1)[0]], ["stand"])
r_oid, r_tok = j["order"], j["token"] r_oid, r_tok = j["order"], j["token"]
+2 -1
View File
@@ -496,7 +496,8 @@ const STN={unpaid:'待付款',paid:'买家说付好了',waiting:'排队中',work
const STC={unpaid:'n',paid:'g',waiting:'b',working:'b',done:'g',failed:'r',void:'n'}; const STC={unpaid:'n',paid:'g',waiting:'b',working:'b',done:'g',failed:'r',void:'n'};
const CSTN={active:'还没用',inactive:'停用',bound:'已激活',used:'已核销'}; const CSTN={active:'还没用',inactive:'停用',bound:'已激活',used:'已核销'};
const CSTC={active:'g',inactive:'n',bound:'b',used:'n'}; const CSTC={active:'g',inactive:'n',bound:'b',used:'n'};
function esc(s){const d=document.createElement('div');d.textContent=s==null?'':String(s);return d.innerHTML;} /* 转义:连引号一起转(2026-10-06 安全加固:原来用 textContent 只转 <>&,放进属性里会被买家写的备注撑破) */
function esc(s){return String(s==null?'':s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));}
function when(s){return String(s||'').replace('T',' ').slice(5,16);} function when(s){return String(s||'').replace('T',' ').slice(5,16);}
function toast(t){const e=$('#toast');e.textContent=t;e.classList.add('on');clearTimeout(e._t);e._t=setTimeout(()=>e.classList.remove('on'),2600);} function toast(t){const e=$('#toast');e.textContent=t;e.classList.add('on');clearTimeout(e._t);e._t=setTimeout(()=>e.classList.remove('on'),2600);}
function copytxt(t,what){ function copytxt(t,what){
+33
View File
@@ -132,3 +132,36 @@ location /order/ {
防护全在后端自己的限流 + 两把令牌 + 来源 IP 门上。 防护全在后端自己的限流 + 两把令牌 + 来源 IP 门上。
- **没做多机/负载均衡**:单机单进程,够用。 - **没做多机/负载均衡**:单机单进程,够用。
- **HTTPS 用自动签发的证书**,续期自动化,没有额外动作。 - **HTTPS 用自动签发的证书**,续期自动化,没有额外动作。
## ⑤ 安全加固(2026-10-06,线上已加)
```nginx
# 文件:/etc/nginx/snippets/jz-sec-base.conf
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=()" always;
# 文件:/etc/nginx/snippets/jz-sec-csp.conf(只给本站页面)
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; media-src 'self' blob:; font-src 'self' data:; connect-src 'self'; frame-src https://player.bilibili.com; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'" always;
# server 块里:
include snippets/jz-sec-base.conf;
include snippets/jz-sec-csp.conf;
location ~* (\.bak[^/]*|\.maint[^/]*|\.old[^/]*|\.orig|\.swp|~|\.v[0-9]+-(live|new)[^/]*)$ { return 404; }
location ~* ^/(order/)?preview-[^/]*\.html$ { return 404; }
location ~ /\.(?!well-known/) { return 404; }
location = /content/site.json { return 404; }
location = /order/content/order.json { return 404; }
# 回调单独限流(http 级:limit_req_zone $binary_remote_addr zone=jzhook:1m rate=20r/m;)
location ~ ^/order/api/(payplatform|afdian)-hook$ {
limit_req zone=jzhook burst=10 nodelay; limit_req_status 429; client_max_body_size 64k;
rewrite ^/order/api/(.*)$ /api/$1 break; proxy_pass http://localhost:<PORT>;
proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr;
add_header Cache-Control "no-store" always; include snippets/jz-sec-base.conf;
}
# ⚠️ 每个自己写了 add_header 的 location 里都要再 include 上面两个文件(nginx 不继承 server 级的 add_header)
# nginx.conf 的 http 块:server_tokens off;
```