feat: 迁移 ADB 设备信息提取
This commit is contained in:
+2
-2
@@ -1,9 +1,9 @@
|
||||
# 复制为 .env 并填入真实值(.env 已被 .gitignore 忽略,请勿提交)
|
||||
ICENTER_ACCOUNT=你的工号
|
||||
ICENTER_PASSWORD=你的密码
|
||||
# 登录成功后写入。也可继续用 tools/extract_token.py 从抓包更新。
|
||||
# 登录成功后会自动写回。
|
||||
ICENTER_TOKEN=
|
||||
# 登录使用的设备身份。手机接上 ADB 后运行 tools/extract_device.py --write 可自动回填。
|
||||
# 登录使用的设备身份。手机接上 ADB 后运行 cargo run --bin extract-device -- --write 可自动回填。
|
||||
# APP 升级时改版本号;更换手机时改设备号。留空则用代码里的当前手机默认值。
|
||||
ICENTER_APP_ID=
|
||||
ICENTER_DEVICE_ID=
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
```powershell
|
||||
cargo run
|
||||
cargo run --bin extract-device -- --write
|
||||
```
|
||||
|
||||
第二条需要手机打开 USB 调试并具有 root,用来把当前 iCenter 的版本和设备身份写回 `.env`。
|
||||
|
||||
账号、密码、token、项目和设备身份放在项目根目录的 `.env`,参考 `.env.example`。token 失效时会用账号密码重新登录。
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
use std::process::ExitCode;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(err) => {
|
||||
eprintln!("{err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> punchlog::Result<()> {
|
||||
let write = std::env::args().any(|arg| arg == "--write");
|
||||
let phone = punchlog::read_phone()?;
|
||||
println!("应用 com.zte.softda {} ({})", phone.version_name, phone.version_code);
|
||||
println!("设备 {}", phone.device_name);
|
||||
println!("deviceId {}", phone.device_id);
|
||||
println!("androidId {}", phone.android_id);
|
||||
println!("deviceNum {}", phone.device_num);
|
||||
if write {
|
||||
let path = punchlog::save_phone(&phone)?;
|
||||
println!("已写入 {}", path.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+32
-14
@@ -135,26 +135,44 @@ impl AppConfig {
|
||||
/// 把新 token 写回找到的 `.env`,方便下次直接使用。
|
||||
pub fn store_token(&mut self, token: &str) -> Result<()> {
|
||||
self.token = token.to_string();
|
||||
let Some(path) = &self.env_path else {
|
||||
if self.env_path.is_none() {
|
||||
return Ok(());
|
||||
};
|
||||
let text = fs::read_to_string(path).unwrap_or_default();
|
||||
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
|
||||
let mut found = false;
|
||||
for line in &mut lines {
|
||||
if line.trim_start().starts_with("ICENTER_TOKEN=") {
|
||||
*line = format!("ICENTER_TOKEN={token}");
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
lines.push(format!("ICENTER_TOKEN={token}"));
|
||||
}
|
||||
fs::write(path, lines.join("\n") + "\n")?;
|
||||
write_env(&[("ICENTER_TOKEN", token)])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新 `.env` 里已有的键,没有的键追加到末尾。账号和密码不会被这里自动改掉。
|
||||
pub fn write_env(values: &[(&str, &str)]) -> Result<PathBuf> {
|
||||
let path = find_env().ok_or_else(|| Error::MissingConfig("找不到 .env".into()))?;
|
||||
let text = fs::read_to_string(&path).unwrap_or_default();
|
||||
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
|
||||
let mut pending: Vec<(&str, &str)> = values.to_vec();
|
||||
for line in &mut lines {
|
||||
let stripped = line.trim_start();
|
||||
if stripped.starts_with('#') || !stripped.contains('=') {
|
||||
continue;
|
||||
}
|
||||
let Some((key, _)) = stripped.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
if let Some(index) = pending.iter().position(|(name, _)| *name == key.trim()) {
|
||||
let (_, value) = pending.remove(index);
|
||||
*line = format!("{}={value}", key.trim());
|
||||
}
|
||||
}
|
||||
for (key, value) in pending {
|
||||
lines.push(format!("{key}={value}"));
|
||||
}
|
||||
fs::write(&path, lines.join("\n") + "\n")?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
pub fn env_path() -> Option<PathBuf> {
|
||||
find_env()
|
||||
}
|
||||
|
||||
fn find_env() -> Option<PathBuf> {
|
||||
let mut dir = env::current_dir().ok()?;
|
||||
loop {
|
||||
|
||||
@@ -18,6 +18,8 @@ pub enum Error {
|
||||
Crypto(String),
|
||||
#[error("解析响应失败: {0}")]
|
||||
Parse(String),
|
||||
#[error("读取手机失败: {0}")]
|
||||
Phone(String),
|
||||
#[error("{0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ mod config;
|
||||
mod error;
|
||||
mod iepms;
|
||||
mod msa;
|
||||
mod phone;
|
||||
mod record;
|
||||
mod report;
|
||||
|
||||
@@ -14,5 +15,6 @@ pub use auth::{login, LoginSession};
|
||||
pub use config::{AppConfig, DeviceProfile};
|
||||
pub use error::{Error, Result};
|
||||
pub use iepms::IepmsClient;
|
||||
pub use phone::{read_phone, save_phone, PhoneIdentity};
|
||||
pub use record::PunchRecord;
|
||||
pub use report::{load_last_week, WeekReport};
|
||||
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
//! 从已 root 的手机读取 iCenter 的版本和设备身份。
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
use aes_gcm::aead::{Aead, KeyInit};
|
||||
use aes_gcm::{Aes256Gcm, Nonce};
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use base64::Engine;
|
||||
|
||||
use crate::config::{self, OwnedDevice};
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
const PACKAGE: &str = "com.zte.softda";
|
||||
const APP_ID: &str = "A00154";
|
||||
const AID_FILE: &str = "/storage/emulated/0/Android/data/com.zte.softda/files/.cn.com.zte.uac.config/aid_deviceid_gcm.cfg";
|
||||
const MMKV_DEVICE: &str = "/data/data/com.zte.softda/files/mmkv/icenter_device_id";
|
||||
/// `libztencrypt.so` 里的 `getKey32()`,用来解开本机保存的 Android ID。
|
||||
const AID_KEY: &[u8] = b"zmailzte12345678zmailzte12345678";
|
||||
|
||||
/// 手机上当前安装的 iCenter 和这台设备的登录身份。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PhoneIdentity {
|
||||
pub app_id: String,
|
||||
pub device_id: String,
|
||||
pub device_num: String,
|
||||
pub brand: String,
|
||||
pub model: String,
|
||||
pub device_name: String,
|
||||
pub android_id: String,
|
||||
pub version_name: String,
|
||||
pub version_code: i64,
|
||||
}
|
||||
|
||||
impl PhoneIdentity {
|
||||
pub fn to_device(&self) -> OwnedDevice {
|
||||
OwnedDevice {
|
||||
app_id: self.app_id.clone(),
|
||||
device_id: self.device_id.clone(),
|
||||
device_num: self.device_num.clone(),
|
||||
device_brand: self.brand.clone(),
|
||||
device_mode: self.model.clone(),
|
||||
device_name: self.device_name.clone(),
|
||||
android_id: self.android_id.clone(),
|
||||
client_ip: "0.0.0.0".into(),
|
||||
version_name: self.version_name.clone(),
|
||||
version_code: self.version_code,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 通过 ADB 读取设备身份。需要 USB 调试和 root。
|
||||
pub fn read_phone() -> Result<PhoneIdentity> {
|
||||
require_device()?;
|
||||
let pkg = adb_text(&["shell", "dumpsys", "package", PACKAGE])?;
|
||||
let version_name = first_match(&pkg, "versionName=", |rest| {
|
||||
rest.split_whitespace().next().unwrap_or("").to_string()
|
||||
})?;
|
||||
let version_code: i64 = first_match(&pkg, "versionCode=", |rest| {
|
||||
rest.chars().take_while(|c| c.is_ascii_digit()).collect()
|
||||
})?
|
||||
.parse()
|
||||
.map_err(|_| Error::Phone("读不到 versionCode".into()))?;
|
||||
let brand = adb_text(&["shell", "getprop", "ro.product.brand"])?.trim().to_string();
|
||||
let model = adb_text(&["shell", "getprop", "ro.product.model"])?.trim().to_string();
|
||||
if brand.is_empty() || model.is_empty() {
|
||||
return Err(Error::Phone("读不到手机品牌或型号".into()));
|
||||
}
|
||||
|
||||
let mmkv = su_cat(MMKV_DEVICE)?;
|
||||
let bytes = mmkv.as_bytes();
|
||||
let marker = b"V02_";
|
||||
let mut device_ids = Vec::new();
|
||||
let mut offset = 0;
|
||||
while let Some(found) = bytes[offset..].windows(marker.len()).position(|window| window == marker) {
|
||||
let start = offset + found;
|
||||
let mut end = start + marker.len();
|
||||
while end < bytes.len() && bytes[end].is_ascii_hexdigit() {
|
||||
end += 1;
|
||||
}
|
||||
if let Ok(id) = std::str::from_utf8(&bytes[start..end]) {
|
||||
device_ids.push(id.to_string());
|
||||
}
|
||||
offset = end;
|
||||
}
|
||||
if device_ids.is_empty() {
|
||||
return Err(Error::Phone("没有在 icenter_device_id 里找到 V02 设备号。请先打开一次 iCenter。".into()));
|
||||
}
|
||||
let aid = format!("AID_{}", decrypt_aid(su_cat(AID_FILE)?.trim())?);
|
||||
let mut parts = vec![device_ids[0].clone()];
|
||||
if device_ids.len() > 1 {
|
||||
parts.push(device_ids[1].clone());
|
||||
}
|
||||
parts.push(aid.clone());
|
||||
Ok(PhoneIdentity {
|
||||
app_id: APP_ID.into(),
|
||||
device_id: device_ids[0].clone(),
|
||||
device_num: parts.join(";"),
|
||||
device_name: format!("{brand}-{model}"),
|
||||
brand,
|
||||
model,
|
||||
android_id: aid,
|
||||
version_name,
|
||||
version_code,
|
||||
})
|
||||
}
|
||||
|
||||
/// 把设备身份写回 `.env`。不改账号、密码、token 和项目编号;没有 clientIp 时补上 `0.0.0.0`。
|
||||
pub fn save_phone(identity: &PhoneIdentity) -> Result<std::path::PathBuf> {
|
||||
let mut values = vec![
|
||||
("ICENTER_APP_ID", identity.app_id.as_str()),
|
||||
("ICENTER_DEVICE_ID", identity.device_id.as_str()),
|
||||
("ICENTER_DEVICE_NUM", identity.device_num.as_str()),
|
||||
("ICENTER_DEVICE_BRAND", identity.brand.as_str()),
|
||||
("ICENTER_DEVICE_MODE", identity.model.as_str()),
|
||||
("ICENTER_DEVICE_NAME", identity.device_name.as_str()),
|
||||
("ICENTER_ANDROID_ID", identity.android_id.as_str()),
|
||||
("ICENTER_VERSION_NAME", identity.version_name.as_str()),
|
||||
];
|
||||
let version_code = identity.version_code.to_string();
|
||||
values.push(("ICENTER_VERSION_CODE", version_code.as_str()));
|
||||
let text = std::fs::read_to_string(config::env_path().ok_or_else(|| Error::MissingConfig("找不到 .env".into()))?).unwrap_or_default();
|
||||
let has_ip = text.lines().any(|line| line.trim_start().starts_with("ICENTER_CLIENT_IP="));
|
||||
if has_ip {
|
||||
config::write_env(&values)
|
||||
} else {
|
||||
let mut owned: Vec<(String, String)> = values.into_iter().map(|(k, v)| (k.into(), v.into())).collect();
|
||||
owned.push(("ICENTER_CLIENT_IP".into(), "0.0.0.0".into()));
|
||||
let refs: Vec<(&str, &str)> = owned.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||
config::write_env(&refs)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decrypt_aid(secret_b64: &str) -> Result<String> {
|
||||
let raw = STANDARD.decode(secret_b64.trim()).map_err(|e| Error::Crypto(e.to_string()))?;
|
||||
if raw.len() <= 12 {
|
||||
return Err(Error::Crypto("Android ID 文件内容太短".into()));
|
||||
}
|
||||
let cipher = Aes256Gcm::new_from_slice(AID_KEY).map_err(|e| Error::Crypto(e.to_string()))?;
|
||||
let plain = cipher
|
||||
.decrypt(Nonce::from_slice(&raw[..12]), raw[12..].as_ref())
|
||||
.map_err(|e| Error::Crypto(e.to_string()))?;
|
||||
let text = String::from_utf8(plain).map_err(|e| Error::Crypto(e.to_string()))?;
|
||||
if !text.chars().all(|c| c.is_ascii_hexdigit() || c == '-') || text.len() < 16 {
|
||||
return Err(Error::Crypto("Android ID 解密结果不像设备标识".into()));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
fn require_device() -> Result<()> {
|
||||
let text = adb_text(&["devices"])?;
|
||||
let serials: Vec<_> = text
|
||||
.lines()
|
||||
.skip(1)
|
||||
.filter_map(|line| {
|
||||
let mut parts = line.split_whitespace();
|
||||
let serial = parts.next()?;
|
||||
let state = parts.next()?;
|
||||
(state == "device").then_some(serial)
|
||||
})
|
||||
.collect();
|
||||
if serials.is_empty() {
|
||||
return Err(Error::Phone("没有已连接的 ADB 设备。请先打开 USB 调试并授权这台电脑。".into()));
|
||||
}
|
||||
if serials.len() > 1 && std::env::var("ANDROID_SERIAL").ok().filter(|v| !v.is_empty()).is_none() {
|
||||
return Err(Error::Phone(format!("连接了多台设备:{}。请设置 ANDROID_SERIAL。", serials.join(", "))));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn su_cat(path: &str) -> Result<String> {
|
||||
let text = adb_text(&["exec-out", "su", "-c", &format!("cat {path}")])?;
|
||||
if text.is_empty() {
|
||||
return Err(Error::Phone(format!("读不到 {path}。需要 root,且 iCenter 至少打开过一次。")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
fn adb_text(args: &[&str]) -> Result<String> {
|
||||
let output = Command::new("adb").args(args).output().map_err(|err| Error::Phone(format!("找不到 adb:{err}")))?;
|
||||
if !output.status.success() {
|
||||
let err = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(Error::Phone(if err.trim().is_empty() { format!("adb {} 失败", args.join(" ")) } else { err.trim().to_string() }));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
|
||||
}
|
||||
|
||||
fn first_match(text: &str, marker: &str, take: impl Fn(&str) -> String) -> Result<String> {
|
||||
text.lines()
|
||||
.find_map(|line| line.trim().split_once(marker).map(|(_, rest)| take(rest)))
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| Error::Phone(format!("读不到 {marker}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn decrypts_known_aid_file() {
|
||||
let secret = "7BgItC57Tif1YACNEHn4xWRhwdbdzIb1zh5FqkijyBOoQ4MuiN4EbFiuFht06qhW1yln6WL/KngXCTocxc1a5w==";
|
||||
assert_eq!(decrypt_aid(secret).unwrap(), "034b7912-c21d-3bb3-9bfe-ea789d753967");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user