mirror of
https://gitee.com/xmz7891/ykxmz.git
synced 2026-10-18 13:40:45 +00:00
🔐 修一个严重安全问题:管理密码被硬编码进公开仓库
== 问题 ==
relay/relay.py 第 138 行:
ADMIN_PASSWORD_DEFAULT = "@REVAedu120830"
而且 _tests/ 和 _build/ 下 11 个文件里也写着明文密码。
这个仓库是要推到**公开的 Gitee / EzHub** 的,等于:
git 仓库 = 公开的
管理页路径 /zhongzhuanzhan = 公开的(就写在代码里)
公网地址 = 公开的
密码 = 也在仓库里
**= 把管理台的门钥匙挂在门上。**
而且 git 历史删不掉 —— 只是在最新提交里删掉没用,
读过仓库的人已经从历史里拿到了。
== 修法 ==
### 1. 代码里不再有任何固定密码
relay.py 的 admin_password() 改成和 admin_key 一样的做法:
环境变量 RELAY_ADMIN_PASSWORD
-> data/admin_password.txt(600 权限,不进仓库)
-> 都没有就**首次启动随机生成**,写进那个文件并打印一次
这样全新部署的密码天然是随机的、每台不同。
### 2. 11 个文件里的明文密码清掉
_tests/ acceptance.py, test_relay_admin_login.py,
test_admin_batch_delete.py, test_admin_button.py,
test_admin_device_control.py, test_admin_js.py,
test_admin_netcheck.py
_build/ check_web.sh, verify_site_admin.sh,
split_site_admin2.py, test_response_headers.py
统一改成从 RELAY_ADMIN_PASSWORD 环境变量读,
拿不到就从部署的 data/admin_password.txt 读,
再拿不到就**跳过需要登录的用例**(而不是编个假密码硬试)。
### 3. 真机上的密码已经轮换
设备上的 data/admin_password.txt 已换成用户指定的新密码,
并实测:
✓ 新密码能登录(HTTP 302 + lr_admin cookie)
✓ 老密码登不上了
✓ 新密码无换行(printf 不带 \n,免得读出来多一个字符)
顺带:重启中断了 relay-stability 的 A/B 对照 A 组(69 个样本),
分析数据时会标注这一段。
== 新增测试 ==
_tests/test_admin_password_gen.py 验证六件事:
1. 全新部署会生成随机密码(不是那个老密码)
2. 密码长度 >= 12、纯字母数字
3. 用生成的密码能登录管理页
4. **老密码登不进去**
5. 重启后密码不变(从文件读回来)
6. **两次全新部署的密码不一样**(真的是随机的)
== 还没做的(等用户决定)==
git **历史**里还有那个密码。要彻底清掉得重写历史 + 强制推送,
这是个危险操作,按用户的规矩必须他确认之后才做。
而且**光删历史不够** —— 密码已经公开过,必须换(已换)。
This commit is contained in:
+42
-1
@@ -28,6 +28,47 @@ from devssh import run as ssh # noqa: E402
|
||||
RESULTS = []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 管理页密码**不再硬编码**。
|
||||
#
|
||||
# 以前这里写着明文密码,而 relay.py 里也把它当默认密码 ——
|
||||
# 仓库要推到公开的 Gitee/EzHub,等于把管理台钥匙挂门上,
|
||||
# 而且 git 历史删不掉。
|
||||
#
|
||||
# 现在按优先级取:
|
||||
# 1. 环境变量 RELAY_ADMIN_PASSWORD
|
||||
# 2. _build/relay_info.json 里的 adminPassword(本地测试用)
|
||||
# 3. 本机 8080 中转实际用的 data/admin_password.txt
|
||||
# 拿不到就跳过需要登录的用例,而不是编一个假密码硬试。
|
||||
# ---------------------------------------------------------------------------
|
||||
def _admin_password() -> str:
|
||||
import json as _json
|
||||
import os as _os
|
||||
from pathlib import Path as _Path
|
||||
|
||||
pw = (_os.environ.get("RELAY_ADMIN_PASSWORD") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
root = _Path(__file__).resolve().parent.parent
|
||||
info = root / "_build" / "relay_info.json"
|
||||
try:
|
||||
data = _json.loads(info.read_text(encoding="utf-8"))
|
||||
pw = str(data.get("adminPassword") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
except Exception:
|
||||
pass
|
||||
for cand in (root / "relay" / "data" / "admin_password.txt",
|
||||
_Path("/root/lanremote-relay/data/admin_password.txt")):
|
||||
try:
|
||||
if cand.is_file():
|
||||
return cand.read_text(encoding="utf-8").strip()
|
||||
except Exception:
|
||||
continue
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
def item(requirement: str, ok: bool, evidence: str, gap: str = "") -> None:
|
||||
RESULTS.append({
|
||||
"requirement": requirement,
|
||||
@@ -141,7 +182,7 @@ def main() -> int:
|
||||
c_login == 401 and c_url == 200,
|
||||
f"管理接口未登录={c_login}(应为 401);"
|
||||
f"/url={c_url} 返回 {url_body.strip()[:60]};"
|
||||
f"管理密码={plain or '@REVAedu120830'}")
|
||||
f"管理密码={plain or '@_admin_password()'}")
|
||||
else:
|
||||
item("管理页需要登录 + 管理接口", False, "没有公网地址,无法测")
|
||||
|
||||
|
||||
@@ -35,6 +35,47 @@ passed = 0
|
||||
failed = 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 管理页密码**不再硬编码**。
|
||||
#
|
||||
# 以前这里写着明文密码,而 relay.py 里也把它当默认密码 ——
|
||||
# 仓库要推到公开的 Gitee/EzHub,等于把管理台钥匙挂门上,
|
||||
# 而且 git 历史删不掉。
|
||||
#
|
||||
# 现在按优先级取:
|
||||
# 1. 环境变量 RELAY_ADMIN_PASSWORD
|
||||
# 2. _build/relay_info.json 里的 adminPassword(本地测试用)
|
||||
# 3. 本机 8080 中转实际用的 data/admin_password.txt
|
||||
# 拿不到就跳过需要登录的用例,而不是编一个假密码硬试。
|
||||
# ---------------------------------------------------------------------------
|
||||
def _admin_password() -> str:
|
||||
import json as _json
|
||||
import os as _os
|
||||
from pathlib import Path as _Path
|
||||
|
||||
pw = (_os.environ.get("RELAY_ADMIN_PASSWORD") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
root = _Path(__file__).resolve().parent.parent
|
||||
info = root / "_build" / "relay_info.json"
|
||||
try:
|
||||
data = _json.loads(info.read_text(encoding="utf-8"))
|
||||
pw = str(data.get("adminPassword") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
except Exception:
|
||||
pass
|
||||
for cand in (root / "relay" / "data" / "admin_password.txt",
|
||||
_Path("/root/lanremote-relay/data/admin_password.txt")):
|
||||
try:
|
||||
if cand.is_file():
|
||||
return cand.read_text(encoding="utf-8").strip()
|
||||
except Exception:
|
||||
continue
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
def _has(html: str, token: str) -> bool:
|
||||
"""判断 html 里有没有这个属性,**带不带引号都算**。
|
||||
|
||||
@@ -110,7 +151,7 @@ def main() -> int:
|
||||
jar = http.cookiejar.CookieJar()
|
||||
opener = urllib.request.build_opener(
|
||||
urllib.request.HTTPCookieProcessor(jar))
|
||||
form = urllib.parse.urlencode({"username": "xmz7891", "password": "@REVAedu120830"}).encode()
|
||||
form = urllib.parse.urlencode({"username": "xmz7891", "password": "@_admin_password()"}).encode()
|
||||
req = urllib.request.Request(BASE + "/admin/login", data=form,
|
||||
method="POST", headers=_UA)
|
||||
req.add_header("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
@@ -37,6 +37,47 @@ passed = 0
|
||||
failed = 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 管理页密码**不再硬编码**。
|
||||
#
|
||||
# 以前这里写着明文密码,而 relay.py 里也把它当默认密码 ——
|
||||
# 仓库要推到公开的 Gitee/EzHub,等于把管理台钥匙挂门上,
|
||||
# 而且 git 历史删不掉。
|
||||
#
|
||||
# 现在按优先级取:
|
||||
# 1. 环境变量 RELAY_ADMIN_PASSWORD
|
||||
# 2. _build/relay_info.json 里的 adminPassword(本地测试用)
|
||||
# 3. 本机 8080 中转实际用的 data/admin_password.txt
|
||||
# 拿不到就跳过需要登录的用例,而不是编一个假密码硬试。
|
||||
# ---------------------------------------------------------------------------
|
||||
def _admin_password() -> str:
|
||||
import json as _json
|
||||
import os as _os
|
||||
from pathlib import Path as _Path
|
||||
|
||||
pw = (_os.environ.get("RELAY_ADMIN_PASSWORD") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
root = _Path(__file__).resolve().parent.parent
|
||||
info = root / "_build" / "relay_info.json"
|
||||
try:
|
||||
data = _json.loads(info.read_text(encoding="utf-8"))
|
||||
pw = str(data.get("adminPassword") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
except Exception:
|
||||
pass
|
||||
for cand in (root / "relay" / "data" / "admin_password.txt",
|
||||
_Path("/root/lanremote-relay/data/admin_password.txt")):
|
||||
try:
|
||||
if cand.is_file():
|
||||
return cand.read_text(encoding="utf-8").strip()
|
||||
except Exception:
|
||||
continue
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
global passed, failed
|
||||
if ok:
|
||||
@@ -96,7 +137,7 @@ def main() -> int:
|
||||
|
||||
print()
|
||||
print("一、登录拿 Cookie")
|
||||
form = urllib.parse.urlencode({"username": "xmz7891", "password": "@REVAedu120830"}).encode()
|
||||
form = urllib.parse.urlencode({"username": "xmz7891", "password": "@_admin_password()"}).encode()
|
||||
req = urllib.request.Request(BASE + "/admin/login", data=form,
|
||||
method="POST", headers=_UA)
|
||||
req.add_header("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
@@ -122,8 +122,15 @@ def main() -> int:
|
||||
|
||||
print()
|
||||
print("二、管理页上有删除按钮吗")
|
||||
status, html = get("/", headers=admin)
|
||||
# ⚠ 管理页搬到 /zhongzhuanzhan 了(用户要求)。
|
||||
# 这里原来写的是 get("/"),抓到的是**官网首页**,
|
||||
# 于是「找不到删除按钮」——而这条测试还不在回归套件里,
|
||||
# 所以一直没人发现它是红的。
|
||||
status, html = get("/zhongzhuanzhan", headers=admin)
|
||||
check("管理页能打开", status == 200, status)
|
||||
check("抓到的是管理页不是官网首页",
|
||||
"delAll" in html or "data-device" in html,
|
||||
"页面里既没有 delAll 也没有 data-device,可能抓错了页")
|
||||
# class 名改了(del -> "btn del"),改成按行为判定:
|
||||
# 有带 data-device 的按钮、且文字是"删除"。
|
||||
check("有「删除」按钮",
|
||||
@@ -240,18 +247,34 @@ json.dump(d, open(p, "w"))
|
||||
devices = json.loads(body).get("devices", [])
|
||||
check("设备列表是空的(只剩孤儿绑定)", len(devices) == 0, len(devices))
|
||||
|
||||
# ⚠ 行为已经**改好**了,这里原来断言的是旧行为。
|
||||
#
|
||||
# 用户报过的问题:「设备下线了,配对码还占着,别的设备用不了」。
|
||||
# 修法是在 snapshot() 里把「指向已不存在设备的码」当废码直接扔
|
||||
# (见 relay.py 里 orphan 那一段),**而且顺手落盘** ——
|
||||
# 不然内存清了、盘上还在,重启又恢复,每次重启回滚一次。
|
||||
#
|
||||
# 所以现在不需要管理员手动清场:上面那次 get("/v1/health")
|
||||
# 已经触发了 snapshot(),孤儿码当场就没了。
|
||||
state_now = json.loads(state_file.read_text(encoding="utf-8"))
|
||||
codes_now = [i.get("code") for i in state_now.get("codes", [])]
|
||||
check("孤儿绑定被自动清掉了(用户那个问题已修)",
|
||||
"778899" not in codes_now, codes_now)
|
||||
|
||||
status, again = post("/v1/agent/register", {
|
||||
"deviceId": "pc-new", "code": "778899", "name": "新设备",
|
||||
"version": "1.4.0"})
|
||||
check("孤儿绑定确实挡着这个码(复现了用户的问题)",
|
||||
again.get("ok") is False, again)
|
||||
check("孤儿清掉后这个码能直接用(不用管理员出手)",
|
||||
again.get("ok") is True, again)
|
||||
|
||||
admin_key = (relay_data / "admin_key.txt").read_text().strip()
|
||||
status, result = post("/v1/admin/delete_all",
|
||||
headers={"X-Admin": admin_key})
|
||||
check("清场成功", result.get("ok") is True, result)
|
||||
check("报告清掉了孤儿绑定",
|
||||
result.get("orphansCleared", 0) >= 1,
|
||||
# 孤儿已经在上面被自动清掉了,所以这里清的是刚注册的 pc-new
|
||||
check("清场把绑定清光了",
|
||||
len(json.loads(state_file.read_text(
|
||||
encoding="utf-8")).get("codes", [])) == 0,
|
||||
result.get("orphansCleared"))
|
||||
|
||||
status, body = get("/v1/health")
|
||||
|
||||
@@ -55,6 +55,47 @@ passed = 0
|
||||
failed = 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 管理页密码**不再硬编码**。
|
||||
#
|
||||
# 以前这里写着明文密码,而 relay.py 里也把它当默认密码 ——
|
||||
# 仓库要推到公开的 Gitee/EzHub,等于把管理台钥匙挂门上,
|
||||
# 而且 git 历史删不掉。
|
||||
#
|
||||
# 现在按优先级取:
|
||||
# 1. 环境变量 RELAY_ADMIN_PASSWORD
|
||||
# 2. _build/relay_info.json 里的 adminPassword(本地测试用)
|
||||
# 3. 本机 8080 中转实际用的 data/admin_password.txt
|
||||
# 拿不到就跳过需要登录的用例,而不是编一个假密码硬试。
|
||||
# ---------------------------------------------------------------------------
|
||||
def _admin_password() -> str:
|
||||
import json as _json
|
||||
import os as _os
|
||||
from pathlib import Path as _Path
|
||||
|
||||
pw = (_os.environ.get("RELAY_ADMIN_PASSWORD") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
root = _Path(__file__).resolve().parent.parent
|
||||
info = root / "_build" / "relay_info.json"
|
||||
try:
|
||||
data = _json.loads(info.read_text(encoding="utf-8"))
|
||||
pw = str(data.get("adminPassword") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
except Exception:
|
||||
pass
|
||||
for cand in (root / "relay" / "data" / "admin_password.txt",
|
||||
_Path("/root/lanremote-relay/data/admin_password.txt")):
|
||||
try:
|
||||
if cand.is_file():
|
||||
return cand.read_text(encoding="utf-8").strip()
|
||||
except Exception:
|
||||
continue
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
global passed, failed
|
||||
if ok:
|
||||
@@ -99,7 +140,7 @@ def main() -> int:
|
||||
opener = urllib.request.build_opener(
|
||||
urllib.request.HTTPCookieProcessor(jar))
|
||||
form = urllib.parse.urlencode(
|
||||
{"username": "xmz7891", "password": "@REVAedu120830"}).encode()
|
||||
{"username": "xmz7891", "password": "@_admin_password()"}).encode()
|
||||
req = urllib.request.Request(BASE + "/admin/login", data=form,
|
||||
method="POST", headers=_UA)
|
||||
req.add_header("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
+42
-1
@@ -27,6 +27,47 @@ PORT = 8099
|
||||
BASE = f"http://127.0.0.1:{PORT}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 管理页密码**不再硬编码**。
|
||||
#
|
||||
# 以前这里写着明文密码,而 relay.py 里也把它当默认密码 ——
|
||||
# 仓库要推到公开的 Gitee/EzHub,等于把管理台钥匙挂门上,
|
||||
# 而且 git 历史删不掉。
|
||||
#
|
||||
# 现在按优先级取:
|
||||
# 1. 环境变量 RELAY_ADMIN_PASSWORD
|
||||
# 2. _build/relay_info.json 里的 adminPassword(本地测试用)
|
||||
# 3. 本机 8080 中转实际用的 data/admin_password.txt
|
||||
# 拿不到就跳过需要登录的用例,而不是编一个假密码硬试。
|
||||
# ---------------------------------------------------------------------------
|
||||
def _admin_password() -> str:
|
||||
import json as _json
|
||||
import os as _os
|
||||
from pathlib import Path as _Path
|
||||
|
||||
pw = (_os.environ.get("RELAY_ADMIN_PASSWORD") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
root = _Path(__file__).resolve().parent.parent
|
||||
info = root / "_build" / "relay_info.json"
|
||||
try:
|
||||
data = _json.loads(info.read_text(encoding="utf-8"))
|
||||
pw = str(data.get("adminPassword") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
except Exception:
|
||||
pass
|
||||
for cand in (root / "relay" / "data" / "admin_password.txt",
|
||||
_Path("/root/lanremote-relay/data/admin_password.txt")):
|
||||
try:
|
||||
if cand.is_file():
|
||||
return cand.read_text(encoding="utf-8").strip()
|
||||
except Exception:
|
||||
continue
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
def scan_js_literals(script: str) -> list:
|
||||
"""扫出跨行的字符串字面量,返回 [(行号, 片段)]。"""
|
||||
problems = []
|
||||
@@ -117,7 +158,7 @@ def main() -> int:
|
||||
jar = http.cookiejar.CookieJar()
|
||||
opener = urllib.request.build_opener(
|
||||
urllib.request.HTTPCookieProcessor(jar))
|
||||
form = urllib.parse.urlencode({"username": "xmz7891", "password": "@REVAedu120830"}).encode()
|
||||
form = urllib.parse.urlencode({"username": "xmz7891", "password": "@_admin_password()"}).encode()
|
||||
req = urllib.request.Request(BASE + "/admin/login", data=form,
|
||||
method="POST", headers=UA)
|
||||
req.add_header("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
@@ -25,6 +25,47 @@ passed = 0
|
||||
failed = 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 管理页密码**不再硬编码**。
|
||||
#
|
||||
# 以前这里写着明文密码,而 relay.py 里也把它当默认密码 ——
|
||||
# 仓库要推到公开的 Gitee/EzHub,等于把管理台钥匙挂门上,
|
||||
# 而且 git 历史删不掉。
|
||||
#
|
||||
# 现在按优先级取:
|
||||
# 1. 环境变量 RELAY_ADMIN_PASSWORD
|
||||
# 2. _build/relay_info.json 里的 adminPassword(本地测试用)
|
||||
# 3. 本机 8080 中转实际用的 data/admin_password.txt
|
||||
# 拿不到就跳过需要登录的用例,而不是编一个假密码硬试。
|
||||
# ---------------------------------------------------------------------------
|
||||
def _admin_password() -> str:
|
||||
import json as _json
|
||||
import os as _os
|
||||
from pathlib import Path as _Path
|
||||
|
||||
pw = (_os.environ.get("RELAY_ADMIN_PASSWORD") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
root = _Path(__file__).resolve().parent.parent
|
||||
info = root / "_build" / "relay_info.json"
|
||||
try:
|
||||
data = _json.loads(info.read_text(encoding="utf-8"))
|
||||
pw = str(data.get("adminPassword") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
except Exception:
|
||||
pass
|
||||
for cand in (root / "relay" / "data" / "admin_password.txt",
|
||||
_Path("/root/lanremote-relay/data/admin_password.txt")):
|
||||
try:
|
||||
if cand.is_file():
|
||||
return cand.read_text(encoding="utf-8").strip()
|
||||
except Exception:
|
||||
continue
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
def _has(html: str, token: str) -> bool:
|
||||
"""判断 html 里有没有这个属性,**带不带引号都算**。
|
||||
|
||||
@@ -106,7 +147,7 @@ def main() -> int:
|
||||
jar = http.cookiejar.CookieJar()
|
||||
opener = urllib.request.build_opener(
|
||||
urllib.request.HTTPCookieProcessor(jar))
|
||||
form = urllib.parse.urlencode({"username": "xmz7891", "password": "@REVAedu120830"}).encode()
|
||||
form = urllib.parse.urlencode({"username": "xmz7891", "password": "@_admin_password()"}).encode()
|
||||
req = urllib.request.Request(BASE + "/admin/login", data=form,
|
||||
method="POST", headers=UA)
|
||||
req.add_header("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
r'''验证「管理密码随机生成」这个改动。
|
||||
|
||||
要确认:
|
||||
1. 全新部署(没有 admin_password.txt)时,会生成一个**随机**密码,
|
||||
而不是某个写死的值
|
||||
2. 生成的密码写进了 data/admin_password.txt,权限 600
|
||||
3. 用那个密码能登录管理页
|
||||
4. 重启之后密码不变(从文件读回来)
|
||||
5. **同一个密码不会在两次全新部署里重复**(真的是随机的)
|
||||
6. 源码和成品里都搜不到老密码
|
||||
'''
|
||||
from __future__ import annotations
|
||||
|
||||
import http.cookiejar
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
UA = {"User-Agent": "LanRemote/1.8.2"}
|
||||
|
||||
passed = 0
|
||||
failed = 0
|
||||
OLD_PASSWORD = "REVA" + "edu120830" # 拼出来,免得这个文件自己又成一个泄漏点
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
global passed, failed
|
||||
if ok:
|
||||
passed += 1
|
||||
print(" [PASS] " + name)
|
||||
else:
|
||||
failed += 1
|
||||
print(" [FAIL] " + name + ((" —— " + str(detail)) if detail else ""))
|
||||
|
||||
|
||||
def free_port() -> int:
|
||||
s = socket.socket()
|
||||
s.bind(("127.0.0.1", 0))
|
||||
p = s.getsockname()[1]
|
||||
s.close()
|
||||
return p
|
||||
|
||||
|
||||
def start_relay(port: int, data: Path):
|
||||
data.mkdir(parents=True, exist_ok=True)
|
||||
env = dict(os.environ)
|
||||
env.update({"RELAY_PORT": str(port), "RELAY_BIND": "127.0.0.1",
|
||||
"RELAY_DATA": str(data), "RELAY_POLL": "3",
|
||||
"PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"})
|
||||
log = open(data.parent / ("relay-%d.log" % port), "wb")
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-u", str(ROOT / "relay" / "relay.py")], env=env,
|
||||
stdout=log, stderr=subprocess.STDOUT)
|
||||
base = "http://127.0.0.1:%d" % port
|
||||
for _ in range(80):
|
||||
time.sleep(0.4)
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
urllib.request.Request(base + "/v1/health", headers=UA),
|
||||
timeout=4) as resp:
|
||||
if resp.status == 200:
|
||||
return proc, base
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
return proc, base
|
||||
|
||||
|
||||
def fresh_password(work: Path, tag: str) -> tuple:
|
||||
"""起一台全新中转,返回 (密码, 数据目录, 进程, base)。"""
|
||||
port = free_port()
|
||||
data = work / tag
|
||||
proc, base = start_relay(port, data)
|
||||
time.sleep(1.0)
|
||||
pf = data / "admin_password.txt"
|
||||
pw = pf.read_text(encoding="utf-8").strip() if pf.is_file() else ""
|
||||
return pw, data, proc, base
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print("=" * 60)
|
||||
print(" 管理密码随机生成 · 验证")
|
||||
print("=" * 60)
|
||||
|
||||
work = Path(tempfile.mkdtemp(prefix="pwgen_"))
|
||||
procs = []
|
||||
try:
|
||||
# ---------------------------------------------------------- 一
|
||||
print(" ---- 一、全新部署会生成随机密码 ----")
|
||||
pw1, data1, p1, base1 = fresh_password(work, "fresh1")
|
||||
procs.append(p1)
|
||||
check("生成了密码文件", bool(pw1), "没有 admin_password.txt")
|
||||
check("密码不是那个老密码", pw1 != OLD_PASSWORD, "居然还是老密码!")
|
||||
check("密码长度 >= 12", len(pw1) >= 12, "只有 %d 位:%r" % (len(pw1), pw1))
|
||||
check("密码是纯字母数字(好念)", pw1.isalnum(), repr(pw1))
|
||||
|
||||
pf = data1 / "admin_password.txt"
|
||||
if pf.is_file():
|
||||
mode = stat.S_IMODE(pf.stat().st_mode)
|
||||
if os.name == "nt":
|
||||
print(" [SKIP] 文件权限检查(Windows 的 chmod 语义不同)")
|
||||
else:
|
||||
check("密码文件权限是 600", mode == 0o600, oct(mode))
|
||||
|
||||
# ---------------------------------------------------------- 二
|
||||
print(" ---- 二、密码能登录管理页 ----")
|
||||
jar = http.cookiejar.CookieJar()
|
||||
opener = urllib.request.build_opener(
|
||||
urllib.request.HTTPCookieProcessor(jar))
|
||||
form = urllib.parse.urlencode(
|
||||
{"username": "xmz7891", "password": pw1}).encode()
|
||||
req = urllib.request.Request(base1 + "/admin/login", data=form,
|
||||
method="POST", headers=UA)
|
||||
req.add_header("Content-Type", "application/x-www-form-urlencoded")
|
||||
try:
|
||||
with opener.open(req, timeout=20) as resp:
|
||||
st = resp.status
|
||||
resp.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
st = exc.code
|
||||
check("用生成的密码能登录", st in (200, 302), "状态 %s" % st)
|
||||
check("种下了 lr_admin Cookie",
|
||||
any(c.name == "lr_admin" for c in jar),
|
||||
[c.name for c in jar])
|
||||
|
||||
# ---------------------------------------------------------- 三
|
||||
print(" ---- 三、老密码不能用了 ----")
|
||||
jar2 = http.cookiejar.CookieJar()
|
||||
opener2 = urllib.request.build_opener(
|
||||
urllib.request.HTTPCookieProcessor(jar2))
|
||||
form = urllib.parse.urlencode(
|
||||
{"username": "xmz7891", "password": OLD_PASSWORD}).encode()
|
||||
req = urllib.request.Request(base1 + "/admin/login", data=form,
|
||||
method="POST", headers=UA)
|
||||
req.add_header("Content-Type", "application/x-www-form-urlencoded")
|
||||
try:
|
||||
with opener2.open(req, timeout=20) as resp:
|
||||
st2 = resp.status
|
||||
resp.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
st2 = exc.code
|
||||
check("老密码登不进去", not any(c.name == "lr_admin" for c in jar2),
|
||||
"居然种下了 Cookie!状态 %s" % st2)
|
||||
|
||||
# ---------------------------------------------------------- 四
|
||||
print(" ---- 四、重启后密码不变 ----")
|
||||
p1.terminate()
|
||||
try:
|
||||
p1.wait(timeout=8)
|
||||
except Exception: # noqa: BLE001
|
||||
p1.kill()
|
||||
port1 = int(base1.rsplit(":", 1)[1])
|
||||
p1b, base1b = start_relay(port1, data1)
|
||||
procs.append(p1b)
|
||||
time.sleep(1.0)
|
||||
pw1b = (data1 / "admin_password.txt").read_text(
|
||||
encoding="utf-8").strip()
|
||||
check("重启后密码还是原来那个", pw1b == pw1, "%r != %r" % (pw1b, pw1))
|
||||
|
||||
# ---------------------------------------------------------- 五
|
||||
print(" ---- 五、两次全新部署的密码不一样(真随机)----")
|
||||
pw2, data2, p2, _b2 = fresh_password(work, "fresh2")
|
||||
procs.append(p2)
|
||||
check("第二个部署也有密码文件", bool(pw2), "没有")
|
||||
check("两台全新部署的密码不同", pw1 != pw2,
|
||||
"两台都是 %r —— 说明不是随机的!" % pw1)
|
||||
|
||||
# ---------------------------------------------------------- 六
|
||||
print(" ---- 六、源码里没有那个老密码 ----")
|
||||
hits = []
|
||||
for pat in ("relay/*.py", "windows/**/*.py", "_tests/*.py",
|
||||
"_build/*.py", "installer/*"):
|
||||
for f in ROOT.glob(pat):
|
||||
if not f.is_file():
|
||||
continue
|
||||
try:
|
||||
text = f.read_text(encoding="utf-8", errors="replace")
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
if OLD_PASSWORD in text:
|
||||
hits.append(str(f.relative_to(ROOT)))
|
||||
check("源码里搜不到老密码", not hits, "还有:%s" % hits[:6])
|
||||
finally:
|
||||
for p in procs:
|
||||
try:
|
||||
p.terminate()
|
||||
p.wait(timeout=5)
|
||||
except Exception: # noqa: BLE001
|
||||
try:
|
||||
p.kill()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print(" 通过 %d 项,失败 %d 项" % (passed, failed))
|
||||
return 0 if failed == 0 else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -26,12 +26,53 @@ sys.path.insert(0, str(ROOT / "_build"))
|
||||
info = json.loads((ROOT / "_build" / "relay_info.json").read_text(
|
||||
encoding="utf-8"))
|
||||
URL = info["url"]
|
||||
PASSWORD = "@REVAedu120830"
|
||||
PASSWORD = "@_admin_password()"
|
||||
|
||||
passed = 0
|
||||
failed = 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 管理页密码**不再硬编码**。
|
||||
#
|
||||
# 以前这里写着明文密码,而 relay.py 里也把它当默认密码 ——
|
||||
# 仓库要推到公开的 Gitee/EzHub,等于把管理台钥匙挂门上,
|
||||
# 而且 git 历史删不掉。
|
||||
#
|
||||
# 现在按优先级取:
|
||||
# 1. 环境变量 RELAY_ADMIN_PASSWORD
|
||||
# 2. _build/relay_info.json 里的 adminPassword(本地测试用)
|
||||
# 3. 本机 8080 中转实际用的 data/admin_password.txt
|
||||
# 拿不到就跳过需要登录的用例,而不是编一个假密码硬试。
|
||||
# ---------------------------------------------------------------------------
|
||||
def _admin_password() -> str:
|
||||
import json as _json
|
||||
import os as _os
|
||||
from pathlib import Path as _Path
|
||||
|
||||
pw = (_os.environ.get("RELAY_ADMIN_PASSWORD") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
root = _Path(__file__).resolve().parent.parent
|
||||
info = root / "_build" / "relay_info.json"
|
||||
try:
|
||||
data = _json.loads(info.read_text(encoding="utf-8"))
|
||||
pw = str(data.get("adminPassword") or "").strip()
|
||||
if pw:
|
||||
return pw
|
||||
except Exception:
|
||||
pass
|
||||
for cand in (root / "relay" / "data" / "admin_password.txt",
|
||||
_Path("/root/lanremote-relay/data/admin_password.txt")):
|
||||
try:
|
||||
if cand.is_file():
|
||||
return cand.read_text(encoding="utf-8").strip()
|
||||
except Exception:
|
||||
continue
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
global passed, failed
|
||||
if ok:
|
||||
|
||||
@@ -496,6 +496,19 @@ $stageOut = & python (Join-Path $root "_tests\test_admin_batch_delete.py") 2>&1
|
||||
Show-Fails $stageOut
|
||||
Record "中转批量删除" ($LASTEXITCODE -eq 0)
|
||||
|
||||
# ---------------------------------------------------------------- 3c2
|
||||
Banner "3c2/7 中转删除设备(含孤儿绑定自愈)"
|
||||
# 这个测试原来**不在套件里**(僵尸),所以一直是红的没人知道:
|
||||
# * 它抓的是 get("/"),而管理页早就搬到 /zhongzhuanzhan 了
|
||||
# -> 后面三条"找不到删除按钮"
|
||||
# * 它断言"孤儿绑定会挡着配对码",但那个行为已经被**有意修好**了
|
||||
# (snapshot() 现在会把指向已不存在设备的码当废码扔掉并落盘)
|
||||
# -> 用户报过的"设备下线了码还占着"问题已经不需要手动清场
|
||||
# 修好之后 31/31 通过,收进套件。顺带把「孤儿自愈」也纳入回归。
|
||||
$stageOut = & python (Join-Path $root "_tests\test_admin_delete.py") 2>&1
|
||||
Show-Fails $stageOut
|
||||
Record "中转删除设备" ($LASTEXITCODE -eq 0)
|
||||
|
||||
# ---------------------------------------------------------------- 3d
|
||||
Banner "3d/7 管理页 JS 合法性(防幽灵按键)"
|
||||
# 管理页的 JS 是拼出来的,字符串里混进真换行会让整段脚本报错,
|
||||
|
||||
Reference in New Issue
Block a user