From 87af63a9c025e8bd55d674567ab6dc142db54e7a Mon Sep 17 00:00:00 2001 From: Nixevol Date: Fri, 6 Nov 2026 17:46:58 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=89=93=E5=8D=A1=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E6=8B=89=E5=8F=96/=E7=BC=BA=E5=8D=A1=E7=BB=9F=E8=AE=A1?= =?UTF-8?q?=E5=B7=A5=E5=85=B7(iEPMS=20token=E7=9B=B4=E8=BF=9E,=20=E6=97=A0?= =?UTF-8?q?=E9=9C=80=E7=AD=BE=E5=90=8D)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 10 +++ .gitignore | 3 + pyproject.toml | 21 ++++++ src/punchlog/__init__.py | 1 + src/punchlog/__main__.py | 3 + src/punchlog/analyze.py | 79 +++++++++++++++++++ src/punchlog/auth.py | 147 ++++++++++++++++++++++++++++++++++++ src/punchlog/cli.py | 118 +++++++++++++++++++++++++++++ src/punchlog/config.py | 48 ++++++++++++ src/punchlog/iepms.py | 97 ++++++++++++++++++++++++ src/punchlog/msa.py | 118 +++++++++++++++++++++++++++++ tools/capture/dump_flows.py | 54 +++++++++++++ tools/capture/inject_ca.sh | 35 +++++++++ tools/capture/show.py | 50 ++++++++++++ tools/capture/summarize.py | 26 +++++++ tools/extract_token.py | 81 ++++++++++++++++++++ tools/phone.py | 97 ++++++++++++++++++++++++ 17 files changed, 988 insertions(+) create mode 100644 .env.example create mode 100644 pyproject.toml create mode 100644 src/punchlog/__init__.py create mode 100644 src/punchlog/__main__.py create mode 100644 src/punchlog/analyze.py create mode 100644 src/punchlog/auth.py create mode 100644 src/punchlog/cli.py create mode 100644 src/punchlog/config.py create mode 100644 src/punchlog/iepms.py create mode 100644 src/punchlog/msa.py create mode 100644 tools/capture/dump_flows.py create mode 100644 tools/capture/inject_ca.sh create mode 100644 tools/capture/show.py create mode 100644 tools/capture/summarize.py create mode 100644 tools/extract_token.py create mode 100644 tools/phone.py diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8a19750 --- /dev/null +++ b/.env.example @@ -0,0 +1,10 @@ +# 复制为 .env 并填入真实值(.env 已被 .gitignore 忽略,请勿提交) +ICENTER_ACCOUNT=你的工号 +ICENTER_PASSWORD=你的密码 +# iEPMS token(长效)。从零纯 Python 登录被 EMM 设备绑定拦截("用户设备无效"), +# 故 token 用 tools/extract_token.py 从手机抓包中提取后填这里。 +ICENTER_TOKEN= +# 打卡所属项目/组织(从抓包 listMy 请求或 x-proj-id 头获取) +ICENTER_PROJECT_ID= +ICENTER_ORG_ID=10001 +ICENTER_TENANT_ID=10001 diff --git a/.gitignore b/.gitignore index 5850d16..ea536bf 100644 --- a/.gitignore +++ b/.gitignore @@ -40,5 +40,8 @@ output/ *.db *.sqlite +# Reverse engineering artifacts (第三方 APK、反编译产物、frida/jadx 工具,全部不入库) +reverse/ + # AI docs aidocs/ diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..867fa86 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,21 @@ +[project] +name = "punchlog" +version = "0.1.0" +description = "个人打卡记录拉取、整理与缺卡统计(ZTE iEPMS)" +requires-python = ">=3.10" +dependencies = [ + "requests>=2.28", +] + +[project.optional-dependencies] +crypto = ["cryptography>=41"] + +[project.scripts] +punchlog = "punchlog.cli:main" + +[build-system] +requires = ["setuptools>=61"] +build-backend = "setuptools.build_meta" + +[tool.setuptools.packages.find] +where = ["src"] diff --git a/src/punchlog/__init__.py b/src/punchlog/__init__.py new file mode 100644 index 0000000..9f8197b --- /dev/null +++ b/src/punchlog/__init__.py @@ -0,0 +1 @@ +"""PunchLog: ZTE iCenter punch-record client (pure Python).""" diff --git a/src/punchlog/__main__.py b/src/punchlog/__main__.py new file mode 100644 index 0000000..eb53e2f --- /dev/null +++ b/src/punchlog/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +raise SystemExit(main()) diff --git a/src/punchlog/analyze.py b/src/punchlog/analyze.py new file mode 100644 index 0000000..ac83865 --- /dev/null +++ b/src/punchlog/analyze.py @@ -0,0 +1,79 @@ +"""Analyze punch records: daily summary, missing/insufficient detection, today reminder. + +Rule (user-defined): for each day, take the earliest and the latest punch of that day. +- If the day has fewer than 2 punches -> 缺卡 (insufficient count) +- Else if (latest - earliest) < 8 hours -> 打卡时间不足 (insufficient duration) +- Else -> 正常 (OK) +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, date, timedelta + +MIN_WORK_HOURS = 8.0 +_DT_FMT = "%Y-%m-%d %H:%M:%S" + +STATUS_OK = "正常" +STATUS_FEW = "缺卡(不足2次)" +STATUS_SHORT = "打卡时间不足(<8h)" + + +def _parse_dt(s: str) -> datetime: + return datetime.strptime(s[:19], _DT_FMT) + + +@dataclass +class DaySummary: + day: date + count: int + first: datetime | None + last: datetime | None + hours: float + status: str + records: list = field(default_factory=list) + + @property + def is_problem(self) -> bool: + return self.status != STATUS_OK + + +def daily_summaries(rows: list[dict]) -> list[DaySummary]: + by_day: dict[date, list[dict]] = {} + for r in rows: + sd = r.get("signDate") + if not sd: + continue + try: + dt = _parse_dt(sd) + except ValueError: + continue + r = {**r, "_dt": dt} + by_day.setdefault(dt.date(), []).append(r) + + out: list[DaySummary] = [] + for day in sorted(by_day): + recs = sorted(by_day[day], key=lambda x: x["_dt"]) + first = recs[0]["_dt"] + last = recs[-1]["_dt"] + hours = (last - first).total_seconds() / 3600.0 + if len(recs) < 2: + status = STATUS_FEW + elif hours < MIN_WORK_HOURS: + status = STATUS_SHORT + else: + status = STATUS_OK + out.append(DaySummary(day, len(recs), first, last, hours, status, recs)) + return out + + +def today_status(rows: list[dict], today: date | None = None) -> DaySummary | None: + today = today or datetime.now().date() + for s in daily_summaries(rows): + if s.day == today: + return s + return None + + +def problems(rows: list[dict]) -> list[DaySummary]: + return [s for s in daily_summaries(rows) if s.is_problem] diff --git a/src/punchlog/auth.py b/src/punchlog/auth.py new file mode 100644 index 0000000..3772bf6 --- /dev/null +++ b/src/punchlog/auth.py @@ -0,0 +1,147 @@ +"""ZTE iCenter login (SSO login/pwd) reproduced in pure Python via the MSA envelope. + +Flow (from cn.com.zte.app.ztesso.manager.SSOManager.getResponse + SSOTokenRequest): +1. GET {EMP_BASE}/login/transmissionkey -> bo.publicKey (server RSA transmission key) +2. Build SSOTokenRequest JSON (loginName, loginPwd=plaintext password, device fields, + extendMap={"timestamp": }), MSA-encrypt it and POST to {EMP_BASE}/login/pwd. +3. Decrypt the MSA response -> bo contains the auth token (used as X-Auth-Value). +""" + +from __future__ import annotations + +import json +import time +from dataclasses import dataclass, field + +import requests + +from . import msa + +EMP_BASE = "https://mdm.zte.com.cn/emp/zte-itp-emp-sso" +CONTENT_TYPE = "application/json; charset=utf-8" + +# Device identity captured from the real client (stable per device). +DEFAULT_DEVICE = { + "appId": "A00154", + "deviceId": "V02_CF64B4B1544AC5D3DB79656332385175", + "deviceNum": "V02_CF64B4B1544AC5D3DB79656332385175;V02_CF64B4B1544AC5D3DB79656332385175;AID_034b7912-c21d-3bb3-9bfe-ea789d753967", + "deviceBrand": "Redmi", + "deviceMode": "25053RT47C", + "deviceName": "Redmi 25053RT47C", + "androidId": "034b7912-c21d-3bb3-9bfe-ea789d753967", + "clientIp": "192.168.1.100", + "versionName": "12.8.1", + "versionCode": 120805, +} + + +@dataclass +class Session: + emp_no: str + token: str + tenant_id: str = "10001" + lang_id: str = "zh" + user_info: dict = field(default_factory=dict) + cookies: requests.cookies.RequestsCookieJar = field(default_factory=requests.cookies.RequestsCookieJar) + client_keys: msa.RSAKeyPair | None = None + + +def _get_transmission_key(sess: requests.Session, emp_no: str, tenant_id: str, lang_id: str) -> str: + r = sess.get( + f"{EMP_BASE}/login/transmissionkey", + headers={ + "X-Emp-No": emp_no, + "X-Lang-Id": lang_id, + "X-Tenant-Id": tenant_id, + "Content-Type": CONTENT_TYPE, + "User-Agent": "okhttp/4.12.0", + }, + timeout=30, + ) + r.raise_for_status() + data = r.json() + pub = (data.get("bo") or {}).get("publicKey") + if not pub: + raise RuntimeError(f"transmissionkey failed: {data}") + return pub + + +def _build_login_payload(emp_no: str, password: str, tenant_id: str) -> dict: + """Mirror SSOManager.getResponse + SSOTokenRequest defaults exactly. + + Gson omits null fields, so secretKey/accountId/token are not included. + """ + d = DEFAULT_DEVICE + return { + "loginName": emp_no, + "loginPwd": password, + "appId": d["appId"], # default "A00154" + "deviceBrand": d["deviceBrand"], # Build.BRAND + "deviceMode": d["deviceMode"], # Build.MODEL + "deviceId": d["deviceId"], + "deviceNum": d["deviceNum"], + "androidId": d["androidId"], # getMobileAndroidID (AID uuid) + "deviceType": 1, + "deviceName": d["deviceName"], # Build.BRAND + "-" + Build.MODEL + "os": 0, + "clientIp": d["clientIp"], + "packageName": "com.zte.softda", + "versionName": d["versionName"], + "versionCode": 0, + "sequence": "relogin", # SSOConstant.TYPE_RELOGIN + "extendMap": {"timestamp": str(int(time.time() * 1000))}, + "returnUserInfo": 0, + } + + +def login(emp_no: str, password: str, tenant_id: str = "10001", lang_id: str = "zh") -> Session: + http = requests.Session() + server_pub = _get_transmission_key(http, emp_no, tenant_id, lang_id) + + keys = msa.RSAKeyPair.generate() + local_key = msa.gen_local_key_string() + + payload = _build_login_payload(emp_no, password, tenant_id) + body = msa.encrypt_aes_gcm(json.dumps(payload, separators=(",", ":")), local_key) + data_key = msa.encrypt_rsa(server_pub, local_key) + + r = http.post( + f"{EMP_BASE}/login/pwd", + data=body.encode("utf-8"), + headers={ + "X-Emp-No": emp_no, + "X-MSA-Encrypt-PublicKey": keys.public_b64, + "X-MSA-Encrypt-DataKey": data_key, + "X-Lang-Id": lang_id, + "Client": "android", + "Accept": "application/json", + "X-Tenant-Id": tenant_id, + "Content-Type": CONTENT_TYPE, + "User-Agent": "okhttp/4.12.0", + }, + timeout=30, + ) + r.raise_for_status() + + resp_data_key_hdr = r.headers.get("X-MSA-Encrypt-DataKey") or r.headers.get("x-msa-encrypt-datakey") + if not resp_data_key_hdr: + # Some error responses are plaintext JSON. + raise RuntimeError(f"login/pwd no MSA response header; body={r.text[:300]}") + server_local_key = msa.decrypt_rsa(keys._priv, resp_data_key_hdr) + plain = msa.decrypt_aes_gcm(r.text, server_local_key) + data = json.loads(plain) + + bo = data.get("bo") or {} + token = bo.get("token") or bo.get("authValue") or bo.get("eToken") or bo.get("accessToken") + if not token: + raise RuntimeError(f"login ok but no token in bo keys={list(bo.keys())}; data={json.dumps(data, ensure_ascii=False)[:500]}") + + return Session( + emp_no=emp_no, + token=token, + tenant_id=tenant_id, + lang_id=lang_id, + user_info=bo, + cookies=http.cookies, + client_keys=keys, + ) diff --git a/src/punchlog/cli.py b/src/punchlog/cli.py new file mode 100644 index 0000000..bb3fc6f --- /dev/null +++ b/src/punchlog/cli.py @@ -0,0 +1,118 @@ +"""PunchLog command-line tool. + +Usage examples: + python -m punchlog # 当月记录 + 今日提醒 + 缺卡统计 + python -m punchlog --month 2026-10 # 指定月份 + python -m punchlog --start 2026-10-01 --end 2026-10-31 + python -m punchlog --csv out.csv # 同时导出明细 CSV +""" + +from __future__ import annotations + +import argparse +import csv +from datetime import date, datetime, timedelta + +from .analyze import daily_summaries, today_status, problems, STATUS_OK +from .config import config_from_env +from .iepms import IepmsClient + + +def _month_range(month: str) -> tuple[str, str]: + y, m = (int(x) for x in month.split("-")) + start = date(y, m, 1) + nxt = date(y + (m == 12), (m % 12) + 1, 1) + end = nxt - timedelta(days=1) + return start.isoformat(), end.isoformat() + + +def _default_month() -> str: + return datetime.now().strftime("%Y-%m") + + +def _fmt_t(dt) -> str: + return dt.strftime("%H:%M:%S") if dt else "-" + + +def _memo_oneline(rec: dict) -> str: + return " / ".join(x.strip() for x in (rec.get("memo") or "").replace("\r", "\n").split("\n") if x.strip()) + + +def print_table(summaries) -> None: + print(f"{'日期':<12}{'次数':>4} {'最早':<9}{'最晚':<9}{'时长h':>6} {'状态':<18}站点 / 打卡内容") + print("-" * 110) + for s in summaries: + rec = s.records[-1] if s.records else {} + site = (rec.get("siteName") or "").strip() + memo = _memo_oneline(rec) + extra = (site[:16] + "… " if site else "") + memo + print(f"{s.day.isoformat():<12}{s.count:>4} {_fmt_t(s.first):<9}{_fmt_t(s.last):<9}" + f"{s.hours:>6.1f} {s.status:<18}{extra[:60]}") + + +def export_csv(rows: list[dict], path: str) -> None: + cols = ["signDate", "signType", "distance", "siteCode", "siteName", "memo", "phoneSubmitTime", "status"] + with open(path, "w", newline="", encoding="utf-8-sig") as f: + w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore") + w.writeheader() + for r in sorted(rows, key=lambda x: x.get("signDate") or ""): + w.writerow({k: r.get(k, "") for k in cols}) + + +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser(prog="punchlog", description="个人打卡记录与缺卡统计") + p.add_argument("--month", help="月份 YYYY-MM(默认当月)") + p.add_argument("--start", help="起始日期 YYYY-MM-DD") + p.add_argument("--end", help="结束日期 YYYY-MM-DD", default="") + p.add_argument("--csv", help="导出明细 CSV 到指定路径") + p.add_argument("--env", help=".env 路径") + return p + + +def main(argv=None) -> int: + args = build_parser().parse_args(argv) + if args.start: + start, end = args.start, args.end + else: + start, end = _month_range(args.month or _default_month()) + + cfg = config_from_env(args.env) + client = IepmsClient(cfg) + rows = client.fetch_all(start, end) + + summaries = daily_summaries(rows) + print(f"\n== 打卡记录 {start} ~ {end or '今'}({len(rows)} 条, {len(summaries)} 天)==") + print_table(summaries) + + # 今日提醒 + today = date.today() + today_in_range = start <= today.isoformat() <= (end or "9999") + print("\n== 今日提醒 ==") + if not today_in_range: + print(f"(所选区间 {start}~{end or '今'} 不含今日 {today.isoformat()},跳过今日提醒)") + else: + ts = today_status(rows, today) + if ts is None: + print("⚠ 今天还没有打卡记录!") + elif ts.status == STATUS_OK: + print(f"✓ 今日已打卡 {ts.count} 次,{_fmt_t(ts.first)}~{_fmt_t(ts.last)}({ts.hours:.1f}h),{ts.status}") + else: + print(f"⚠ 今日打卡 {ts.count} 次,{_fmt_t(ts.first)}~{_fmt_t(ts.last)}({ts.hours:.1f}h),{ts.status}") + + # 缺卡统计 + probs = problems(rows) + print(f"\n== 缺卡/不足统计({len(probs)} 天)==") + if not probs: + print("✓ 区间内无缺卡/时间不足。") + for s in probs: + print(f" {s.day.isoformat()} {s.status} 次数={s.count} 时长={s.hours:.1f}h " + f"({_fmt_t(s.first)}~{_fmt_t(s.last)})") + + if args.csv: + export_csv(rows, args.csv) + print(f"\n明细已导出: {args.csv}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/punchlog/config.py b/src/punchlog/config.py new file mode 100644 index 0000000..88cf8f2 --- /dev/null +++ b/src/punchlog/config.py @@ -0,0 +1,48 @@ +"""Load configuration from a .env file (no external dependency).""" + +from __future__ import annotations + +import os +from pathlib import Path + +from .iepms import IepmsConfig + + +def _find_env(start: Path) -> Path | None: + for p in [start, *start.parents]: + f = p / ".env" + if f.is_file(): + return f + return None + + +def load_env(path: str | os.PathLike | None = None) -> dict[str, str]: + env: dict[str, str] = {} + f = Path(path) if path else _find_env(Path(__file__).resolve().parent) + if not f or not Path(f).is_file(): + return env + for line in Path(f).read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + k, v = line.split("=", 1) + env[k.strip()] = v.strip().strip('"').strip("'") + return env + + +def config_from_env(path: str | os.PathLike | None = None) -> IepmsConfig: + env = {**load_env(path), **os.environ} + missing = [k for k in ("ICENTER_ACCOUNT", "ICENTER_TOKEN", "ICENTER_PROJECT_ID") if not env.get(k)] + if missing: + raise SystemExit( + "缺少配置: " + ", ".join(missing) + "\n请在 .env 中设置 ICENTER_ACCOUNT / ICENTER_TOKEN / " + "ICENTER_PROJECT_ID (token 可用 tools/extract_token 从手机提取)。" + ) + return IepmsConfig( + emp_no=env["ICENTER_ACCOUNT"], + token=env["ICENTER_TOKEN"], + project_id=env["ICENTER_PROJECT_ID"], + org_id=env.get("ICENTER_ORG_ID", "10001"), + tenant_id=env.get("ICENTER_TENANT_ID", "10001"), + cookie=env.get("ICENTER_COOKIE", ""), + ) diff --git a/src/punchlog/iepms.py b/src/punchlog/iepms.py new file mode 100644 index 0000000..7e245d1 --- /dev/null +++ b/src/punchlog/iepms.py @@ -0,0 +1,97 @@ +"""iEPMS attendance (sign) client. + +Key finding from reverse engineering + live testing: the iEPMS gateway validates the +``X-Auth-Value`` token but does NOT enforce ``x-auth-signature`` on the attendance +read APIs (listMy returns data with a garbage signature or none at all). So fetching +punch records only requires a valid token. We still send a best-effort signature set +for parity with the app, but it is not required. +""" + +from __future__ import annotations + +import json +import time +from dataclasses import dataclass, field +from typing import Iterator + +import requests + +IEPMS_HOST = "https://iepms.dt.zte.com.cn" +IEPMS_BASE = IEPMS_HOST + "/zte-crm-iepms-basebff" +LIST_MY = IEPMS_BASE + "/zte-iccp-iepms-attendance/app/sign/listMy" + + +@dataclass +class IepmsConfig: + emp_no: str + token: str + project_id: str + org_id: str = "10001" + tenant_id: str = "10001" + authority: str = "EPMS_ADMIN" + lang_id: str = "zh_CN" + cookie: str = "" + + +def _headers(cfg: IepmsConfig) -> dict: + ts = str(int(time.time() * 1000)) + h = { + "content-type": "application/json;charset=UTF-8", + "x-proj-id": cfg.project_id, + "x-itp-value": f"projId={cfg.project_id};route=true;projVer=V3.0", + "x-emp-no": cfg.emp_no, + "x-user-guid": cfg.emp_no, + "internal": "1", + "x-auth-value": cfg.token, + "x-lang-id": cfg.lang_id, + "x-org-id": cfg.org_id, + "x-origin-servicename": "iEPMS", + "x-target-servicename": "zte-iccp-iepms-attendance", + "x-tenant-id": cfg.tenant_id, + "authority": cfg.authority, + "x-auth-timestamp": ts, + "User-Agent": "okhttp/4.12.0", + } + if cfg.cookie: + h["Cookie"] = cfg.cookie + return h + + +class IepmsClient: + def __init__(self, cfg: IepmsConfig, session: requests.Session | None = None): + self.cfg = cfg + self.http = session or requests.Session() + + def list_my(self, start_date: str, end_date: str = "", sign_type: int = 0, + page_num: int = 1, page_size: int = 50) -> dict: + body = { + "projectId": self.cfg.project_id, + "signUserId": self.cfg.emp_no, + "startDate": start_date, + "endDate": end_date, + "signType": sign_type, + "pageSize": page_size, + "pageNum": page_num, + } + r = self.http.post(LIST_MY, data=json.dumps(body), headers=_headers(self.cfg), timeout=30) + r.raise_for_status() + data = r.json() + code = (data.get("code") or {}).get("code") + if code != "0000": + raise RuntimeError(f"listMy failed: {data.get('code')}") + return data.get("bo") or {} + + def fetch_all(self, start_date: str, end_date: str = "", sign_type: int = 0, + page_size: int = 50) -> list[dict]: + """Fetch every page of records in [start_date, end_date].""" + out: list[dict] = [] + page = 1 + while True: + bo = self.list_my(start_date, end_date, sign_type, page, page_size) + rows = bo.get("rows") or [] + out.extend(rows) + total = bo.get("total") or 0 + if len(out) >= total or not rows: + break + page += 1 + return out diff --git a/src/punchlog/msa.py b/src/punchlog/msa.py new file mode 100644 index 0000000..be010ce --- /dev/null +++ b/src/punchlog/msa.py @@ -0,0 +1,118 @@ +"""MSA (ZTE) encryption envelope, reverse-engineered from cn.com.zte.android.util.KmsKeyUtil. + +Scheme summary (fully reproduced in pure Python): +- A per-exchange AES-256 key ``localKeyString``: 32 random uppercase ASCII letters + (A-Z), then base64-encoded. The 32 ASCII bytes ARE the AES key; the base64 text is + what gets passed around as ``dataKeyPlain``. +- Request body: ``AES/GCM/NoPadding`` (12-byte IV, 128-bit tag). Output text is + ``base64(ciphertext+tag) + "$$" + base64(iv)``. +- ``X-MSA-Encrypt-DataKey`` header = RSA-OAEP(SHA-256) encrypt of ``localKeyString`` + using the server's transmission public key (X509 DER, base64). +- ``X-MSA-Encrypt-PublicKey`` header = the client's freshly generated RSA public key + (X509 DER, base64). The server encrypts its response AES key to this key. +- Response body is decrypted by: RSA-OAEP-decrypt the response ``X-MSA-Encrypt-DataKey`` + header with the client private key to recover the server's ``localKeyString``, then + AES-GCM-decrypt the body with it. + +RSA: 2048-bit, OAEP with SHA-256 and MGF1(SHA-256). Encrypt chunk size 245, decrypt 256. +""" + +from __future__ import annotations + +import base64 +import os +import secrets +import string +from dataclasses import dataclass + +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import padding, rsa +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +_OAEP = padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA256()), + algorithm=hashes.SHA256(), + label=None, +) + +RSA_ENC_CHUNK = 245 +RSA_DEC_CHUNK = 256 +SPLIT_FLAG = "$$" + + +def _b64e(b: bytes) -> str: + return base64.b64encode(b).decode("ascii") + + +def _b64d(s: str) -> bytes: + return base64.b64decode(s) + + +def gen_local_key_string() -> str: + """32 random uppercase A-Z chars, base64-encoded (KmsKeyUtil.getLocalKeyString).""" + raw = "".join(secrets.choice(string.ascii_uppercase) for _ in range(32)) + return _b64e(raw.encode("ascii")) + + +@dataclass +class RSAKeyPair: + public_b64: str # X509 SubjectPublicKeyInfo DER, base64 + private_b64: str # PKCS8 DER, base64 + _priv: rsa.RSAPrivateKey + + @classmethod + def generate(cls) -> "RSAKeyPair": + priv = rsa.generate_private_key(public_exponent=65537, key_size=2048) + pub_der = priv.public_key().public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + priv_der = priv.private_bytes( + serialization.Encoding.DER, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + return cls(_b64e(pub_der), _b64e(priv_der), priv) + + +def load_public_from_b64(pub_b64: str): + return serialization.load_der_public_key(_b64d(pub_b64)) + + +def encrypt_rsa(server_pub_b64: str, plaintext: str) -> str: + """RSA-OAEP(SHA-256) encrypt, chunked by 245 bytes, concatenated, base64.""" + pub = load_public_from_b64(server_pub_b64) + data = plaintext.encode("utf-8") + out = bytearray() + for i in range(0, len(data), RSA_ENC_CHUNK): + out += pub.encrypt(data[i:i + RSA_ENC_CHUNK], _OAEP) + return _b64e(bytes(out)) + + +def decrypt_rsa_bytes(priv: rsa.RSAPrivateKey, encrypted_b64: str) -> bytes: + data = _b64d(encrypted_b64) + out = bytearray() + for i in range(0, len(data), RSA_DEC_CHUNK): + out += priv.decrypt(data[i:i + RSA_DEC_CHUNK], _OAEP) + return bytes(out) + + +def decrypt_rsa(priv: rsa.RSAPrivateKey, encrypted_b64: str) -> str: + return decrypt_rsa_bytes(priv, encrypted_b64).decode("utf-8") + + +def encrypt_aes_gcm(plaintext: str, local_key_string: str) -> str: + key = _b64d(local_key_string) # 32 bytes + iv = os.urandom(12) + ct = AESGCM(key).encrypt(iv, plaintext.encode("utf-8"), None) # ct||tag + return _b64e(ct) + SPLIT_FLAG + _b64e(iv) + + +def decrypt_aes_gcm(encrypted_text: str, data_key_plain: str) -> str: + parts = encrypted_text.split(SPLIT_FLAG) + if len(parts) != 2: + raise ValueError("Invalid encrypted text format") + ct = _b64d(parts[0]) + iv = _b64d(parts[1]) + key = _b64d(data_key_plain) + return AESGCM(key).decrypt(iv, ct, None).decode("utf-8") diff --git a/tools/capture/dump_flows.py b/tools/capture/dump_flows.py new file mode 100644 index 0000000..38e3e2b --- /dev/null +++ b/tools/capture/dump_flows.py @@ -0,0 +1,54 @@ +"""mitmproxy addon: append every HTTP flow to a JSONL file. + +Usage: + mitmdump -s tools/capture/dump_flows.py --set dump_path=data/captures/flows.jsonl +""" + +import base64 +import json +import os +import time + +from mitmproxy import ctx, http + + +def _body(message: http.Message | None) -> dict | None: + if message is None: + return None + raw = message.get_content(strict=False) or b"" + try: + return {"text": raw.decode("utf-8"), "size": len(raw)} + except UnicodeDecodeError: + return {"b64": base64.b64encode(raw).decode(), "size": len(raw)} + + +class DumpFlows: + def load(self, loader): + loader.add_option("dump_path", str, "data/captures/flows.jsonl", "JSONL output path") + + def response(self, flow: http.HTTPFlow): + self._write(flow) + + def error(self, flow: http.HTTPFlow): + self._write(flow) + + def _write(self, flow: http.HTTPFlow): + req, resp = flow.request, flow.response + record = { + "ts": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(req.timestamp_start)), + "method": req.method, + "url": req.pretty_url, + "req_headers": list(req.headers.items(multi=True)), + "req_body": _body(req), + "status": resp.status_code if resp else None, + "resp_headers": list(resp.headers.items(multi=True)) if resp else None, + "resp_body": _body(resp), + "error": str(flow.error) if flow.error else None, + } + path = ctx.options.dump_path + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + with open(path, "a", encoding="utf-8") as f: + f.write(json.dumps(record, ensure_ascii=False) + "\n") + + +addons = [DumpFlows()] diff --git a/tools/capture/inject_ca.sh b/tools/capture/inject_ca.sh new file mode 100644 index 0000000..5dd2e83 --- /dev/null +++ b/tools/capture/inject_ca.sh @@ -0,0 +1,35 @@ +#!/system/bin/sh +# Temporarily trust a CA system-wide on Android 14+ (APEX conscrypt store). +# Effective until reboot. Run as root: sh inject_ca.sh /data/local/tmp/.0 +CERT="$1" +DIR=/data/local/tmp/cacerts +APEX=/apex/com.android.conscrypt/cacerts + +[ -f "$CERT" ] || { echo "cert not found: $CERT"; exit 1; } + +rm -rf "$DIR" +mkdir -p "$DIR" +cp "$APEX"/* "$DIR"/ +cp "$CERT" "$DIR"/ +chown -R root:root "$DIR" +chmod 755 "$DIR" +chmod 644 "$DIR"/* +chcon -R u:object_r:system_file:s0 "$DIR" +echo "certs prepared: $(ls "$DIR" | wc -l)" + +bind_into() { + nsenter --mount=/proc/$1/ns/mnt -- /system/bin/mount --bind "$DIR" "$APEX" 2>/dev/null +} + +ZYGOTES="$(pidof zygote) $(pidof zygote64)" +for Z in $ZYGOTES; do + bind_into "$Z" && echo "zygote $Z ok" +done + +for Z in $ZYGOTES; do + for P in $(ps -o PID= -P "$Z"); do + bind_into "$P" & + done +done +wait +echo done diff --git a/tools/capture/show.py b/tools/capture/show.py new file mode 100644 index 0000000..c56cb58 --- /dev/null +++ b/tools/capture/show.py @@ -0,0 +1,50 @@ +"""Print full details of captured flows by index. + +Usage: + python tools/capture/show.py [index ...] [--file flows.jsonl] [--max N] +""" + +import argparse +import json +from pathlib import Path + + +def fmt_body(body: dict | None, limit: int) -> str: + if not body: + return "" + text = body.get("text") + if text is None: + return f"" + try: + text = json.dumps(json.loads(text), ensure_ascii=False, indent=2) + except ValueError: + pass + return text if len(text) <= limit else text[:limit] + f"\n... <{len(text) - limit} more chars>" + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("indexes", nargs="+", type=int) + ap.add_argument("--file", default="data/captures/flows.jsonl") + ap.add_argument("--max", type=int, default=4000) + args = ap.parse_args() + + lines = Path(args.file).read_text(encoding="utf-8").splitlines() + for i in args.indexes: + r = json.loads(lines[i]) + print(f"===== [{i}] {r['ts']} {r['method']} {r['url']}") + print("--- request headers") + for k, v in r["req_headers"]: + print(f"{k}: {v}") + print("--- request body") + print(fmt_body(r["req_body"], args.max)) + print(f"--- response {r['status']} headers") + for k, v in r["resp_headers"] or []: + print(f"{k}: {v}") + print("--- response body") + print(fmt_body(r["resp_body"], args.max)) + print() + + +if __name__ == "__main__": + main() diff --git a/tools/capture/summarize.py b/tools/capture/summarize.py new file mode 100644 index 0000000..f29347b --- /dev/null +++ b/tools/capture/summarize.py @@ -0,0 +1,26 @@ +"""Print a one-line summary for each captured flow. + +Usage: + python tools/capture/summarize.py [flows.jsonl] [keyword ...] +""" + +import json +import sys +from pathlib import Path + + +def main() -> None: + args = sys.argv[1:] + path = Path(args[0]) if args and args[0].endswith(".jsonl") else Path("data/captures/flows.jsonl") + keywords = [a.lower() for a in args if not a.endswith(".jsonl")] + + for i, line in enumerate(path.read_text(encoding="utf-8").splitlines()): + r = json.loads(line) + if keywords and not any(k in line.lower() for k in keywords): + continue + size = (r["resp_body"] or {}).get("size", 0) + print(f"{i:4d} {r['ts'][11:]} {r['method']:6s} {r['status']} {size:7d} {r['url'][:150]}") + + +if __name__ == "__main__": + main() diff --git a/tools/extract_token.py b/tools/extract_token.py new file mode 100644 index 0000000..2fa9ea2 --- /dev/null +++ b/tools/extract_token.py @@ -0,0 +1,81 @@ +"""Extract the latest iEPMS auth token from captured traffic and update .env. + +Why this exists: from-scratch pure-Python login is blocked by EMM device binding +("用户设备无效" / 100301). But the token (``X-Auth-Value``) is long-lived, and the +attendance read API does not enforce the request signature. So the practical refresh +path is: run the phone app through the capture proxy once, then grab the newest token +from the capture file here. + +Usage: + python tools/extract_token.py # read default capture, print token + python tools/extract_token.py --write # also update ICENTER_TOKEN in .env + python tools/extract_token.py --captures path.jsonl +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +DEFAULT_CAPTURES = ROOT / "data" / "captures" / "flows.jsonl" +ENV_PATH = ROOT / ".env" +TOKEN_HEADER = "x-auth-value" + + +def latest_token(captures: Path) -> tuple[str, str] | None: + """Return (token, ts) from the most recent flow carrying an auth token.""" + best: tuple[str, str] | None = None + for line in captures.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line: + continue + try: + fl = json.loads(line) + except json.JSONDecodeError: + continue + for k, v in (fl.get("req_headers") or []): + if k.lower() == TOKEN_HEADER and v and len(v) >= 16: + ts = str(fl.get("ts") or "") + if best is None or ts > best[1]: + best = (v, ts) + return best + + +def update_env(token: str, env_path: Path = ENV_PATH) -> None: + lines = env_path.read_text(encoding="utf-8").splitlines() if env_path.is_file() else [] + out, found = [], False + for ln in lines: + if ln.strip().startswith("ICENTER_TOKEN="): + out.append(f"ICENTER_TOKEN={token}") + found = True + else: + out.append(ln) + if not found: + out.append(f"ICENTER_TOKEN={token}") + env_path.write_text("\n".join(out) + "\n", encoding="utf-8") + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description="提取最新 iEPMS token") + ap.add_argument("--captures", default=str(DEFAULT_CAPTURES)) + ap.add_argument("--write", action="store_true", help="写入 .env 的 ICENTER_TOKEN") + args = ap.parse_args(argv) + + cap = Path(args.captures) + if not cap.is_file(): + raise SystemExit(f"找不到抓包文件: {cap}") + res = latest_token(cap) + if not res: + raise SystemExit("未在抓包中找到 x-auth-value token。请先让手机 App 走代理发一次请求。") + token, ts = res + print(f"最新 token: {token} (ts={ts})") + if args.write: + update_env(token) + print(f"已写入 {ENV_PATH}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/phone.py b/tools/phone.py new file mode 100644 index 0000000..4614ad3 --- /dev/null +++ b/tools/phone.py @@ -0,0 +1,97 @@ +"""Small adb helpers for driving the phone during capture. + +Usage: + python tools/phone.py shot [out.png] # screenshot + python tools/phone.py texts # list visible texts with centers + python tools/phone.py tap # tap first node whose text/desc contains + python tools/phone.py tapxy + python tools/phone.py back + python tools/phone.py bind # bind CA dir into every app process +""" + +import re +import subprocess +import sys +import tempfile +import xml.etree.ElementTree as ET +from pathlib import Path + +PKG = "com.zte.softda" + + +def adb(*args: str, binary: bool = False): + out = subprocess.run(["adb", *args], capture_output=True, check=False) + return out.stdout if binary else out.stdout.decode("utf-8", "replace") + + +def su(cmd: str) -> str: + return adb("shell", f"su -c '{cmd}'") + + +def shot(path: str = "data/screen.png") -> None: + adb("shell", "screencap -p /data/local/tmp/s.png") + adb("pull", "/data/local/tmp/s.png", path) + print(path) + + +def nodes(): + adb("shell", "uiautomator dump /data/local/tmp/ui.xml") + xml = adb("shell", "cat /data/local/tmp/ui.xml") + root = ET.fromstring(xml[xml.index("<"):]) + for n in root.iter("node"): + label = n.get("text") or n.get("content-desc") or "" + m = re.findall(r"\d+", n.get("bounds", "")) + if label and len(m) == 4: + x1, y1, x2, y2 = map(int, m) + yield label, (x1 + x2) // 2, (y1 + y2) // 2 + + +def texts() -> None: + for label, x, y in nodes(): + print(f"{x:5d} {y:5d} {label}") + + +def tap(text: str) -> None: + for label, x, y in nodes(): + if text in label: + adb("shell", "input", "tap", str(x), str(y)) + print(f"tap {label!r} at {x},{y}") + return + print(f"not found: {text}") + sys.exit(1) + + +BIND_SCRIPT = f"""\ +for P in $(ps -A -o PID,NAME | awk '$2 ~ /^{PKG}/ {{print $1}}'); do + grep -q conscrypt/cacerts /proc/$P/mountinfo && continue + nsenter --mount=/proc/$P/ns/mnt -- /system/bin/mount --bind \\ + /data/local/tmp/cacerts /apex/com.android.conscrypt/cacerts && echo "bound $P" +done +""" + + +def bind() -> None: + local = Path(tempfile.gettempdir()) / "bindall.sh" + local.write_bytes(BIND_SCRIPT.encode()) + adb("push", str(local), "/data/local/tmp/bindall.sh") + print(su("sh /data/local/tmp/bindall.sh").strip() or "all processes already bound") + + +def main() -> None: + cmd, *rest = sys.argv[1:] or ["texts"] + if cmd == "shot": + shot(*rest) + elif cmd == "texts": + texts() + elif cmd == "tap": + tap(" ".join(rest)) + elif cmd == "tapxy": + adb("shell", "input", "tap", *rest) + elif cmd == "back": + adb("shell", "input", "keyevent", "4") + elif cmd == "bind": + bind() + + +if __name__ == "__main__": + main()