The master now sends COMMAND_UPDATE to Android hosts: it picks a "Build Client -> Android" APK, checks the ZIP magic and that the package carries this master's fingerprint, then sends [cmd][size][APK][xxh64]. The client verifies length and hash, writes filesDir/update.apk and commits a PackageInstaller session, so the system installer still asks the user to confirm - an app cannot replace itself silently. Write and hash failures come back over TOKEN_CLIENT_MSG, so the master sees why nothing happened instead of a silently dropped packet. Sending the wrong file is what the fingerprint check guards against: a template without the master id installs fine and then cannot connect back. "Send anyway" is offered only after spelling that out, and the client advertises CLIENT_CAP_APK_UPDATE (0x0400) so an old APK gets "install a new build once by hand" instead of a packet it would discard. Also report the real versionName/versionCode at login instead of the hardcoded v1.0.0, add android/tools/verify_update_apk.py (pre-send check of size, ZIP_STORED libs, ABI, package, versionCode and the decrypted CONNECT_ADDRESS, which it still locates after BuildDlg rewrote szFlag), and translate the nine new strings in en_US, zh_TW and de_DE. Verified on the emulator and against the live release server: generate, sign, send, install, and the device reconnects and re-grants screen capture. Language packs are GBK and were appended as bytes. Co-Authored-By: deepseek-flash
260 lines
9.3 KiB
Python
260 lines
9.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Pre-flight check for an Android APK before installing or pushing it as an update.
|
|
|
|
Usage:
|
|
verify_update_apk.py <apk> [--ip 91.99.165.207] [--port 443]
|
|
[--admin 61f04dd637a74ee3] [--cert-sha256 b8ad4ced...]
|
|
[--sdk <AndroidSDK>]
|
|
|
|
Checks:
|
|
* size <= 40MB (server-side SendApkUpdate limit)
|
|
* APK/ZIP, and lib/*/libyama.so stored (not deflated) so the server can patch it
|
|
* each ABI's CONNECT_ADDRESS: IP / port / superAdmin match expectations
|
|
-> 「生成客户端」 checks "encrypt IP" by default, so szServerIP/szPort are
|
|
ciphertext; this script decrypts with StreamCipher(0x12345678), the same
|
|
algorithm the client uses in ServerIP()/ServerPort().
|
|
* dex contains UpdateInstaller (the build can accept COMMAND_UPDATE later)
|
|
* with --sdk: prints package / versionCode / native-code
|
|
|
|
Locating the struct: first by the szFlag plaintext ("Hello, World!" in the pristine
|
|
template), then by the master id string (BuildDlg rewrites szFlag to it), then by
|
|
the superAdmin needle (base = hit - 228), then by the plaintext IP string.
|
|
Exit code 0 = all checks passed, 1 = something failed.
|
|
"""
|
|
import glob
|
|
import os
|
|
import re
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import zipfile
|
|
import zlib
|
|
|
|
MARKERS = [b"Hello, World!\x00"]
|
|
OFF_IP, LEN_IP = 32, 100
|
|
OFF_PORT, LEN_PORT = 132, 8
|
|
OFF_TYPE = 140
|
|
OFF_ENCRYPT = 144
|
|
OFF_ADMIN = 228
|
|
CLIENT_TYPE_ANDROID = 8
|
|
MAX_SIZE = 40 * 1024 * 1024
|
|
|
|
|
|
def arg(name, default=None):
|
|
if name in sys.argv:
|
|
return sys.argv[sys.argv.index(name) + 1]
|
|
return default
|
|
|
|
|
|
def stream_cipher(data, key=0x12345678):
|
|
"""Same as common/ip_enc.h StreamCipher::process (xorshift32 + xor)."""
|
|
state = key
|
|
out = bytearray()
|
|
for b in data:
|
|
state ^= (state << 13) & 0xFFFFFFFF
|
|
state ^= state >> 17
|
|
state ^= (state << 5) & 0xFFFFFFFF
|
|
state &= 0xFFFFFFFF
|
|
out.append(b ^ ((state & 0xFF) ^ ((state >> 8) & 0xFF)))
|
|
return bytes(out)
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print(__doc__)
|
|
return 1
|
|
apk = sys.argv[1]
|
|
want_ip = arg("--ip")
|
|
want_port = arg("--port")
|
|
want_admin = arg("--admin")
|
|
want_cert = (arg("--cert-sha256") or "").replace(":", "").lower()
|
|
sdk = arg("--sdk")
|
|
|
|
fails = []
|
|
|
|
def check(ok, msg):
|
|
print((" OK " if ok else " FAIL ") + msg)
|
|
if not ok:
|
|
fails.append(msg)
|
|
|
|
size = os.path.getsize(apk)
|
|
print("apk: %s (%d bytes)" % (apk, size))
|
|
check(size <= MAX_SIZE, "size %d <= 40MB" % size)
|
|
|
|
with open(apk, "rb") as f:
|
|
head = f.read(4)
|
|
check(head == b"PK\x03\x04", "ZIP magic")
|
|
|
|
z = zipfile.ZipFile(apk)
|
|
infos = z.infolist()
|
|
|
|
def read_entry(name):
|
|
"""z.read() that tolerates a stale CRC-32.
|
|
|
|
BuildDlg patches libyama.so in place without recomputing the ZIP CRC, so
|
|
every generated APK fails zipfile's CRC check even though the payload is
|
|
fine. Read the raw stored bytes instead.
|
|
"""
|
|
try:
|
|
return z.read(name), True
|
|
except zipfile.BadZipFile:
|
|
info = z.getinfo(name)
|
|
with open(apk, "rb") as f:
|
|
f.seek(info.header_offset)
|
|
local = f.read(30)
|
|
if len(local) < 30 or local[:4] != b"PK\x03\x04":
|
|
raise
|
|
nlen, elen = struct.unpack_from("<HH", local, 26)
|
|
f.seek(info.header_offset + 30 + nlen + elen)
|
|
payload = f.read(info.compress_size)
|
|
if info.compress_type == zipfile.ZIP_STORED:
|
|
return payload, False
|
|
return zlib.decompress(payload, -15), False
|
|
sos = [i for i in infos if i.filename.startswith("lib/") and i.filename.endswith("libyama.so")]
|
|
abis = sorted({i.filename.split("/")[1] for i in sos})
|
|
print("abis: %s" % (", ".join(abis) if abis else "none"))
|
|
check(bool(sos), "libyama.so present")
|
|
check("x86" not in abis and "x86_64" not in abis, "no emulator ABIs (production build)")
|
|
|
|
dex_ok = False
|
|
for i in infos:
|
|
if i.filename.startswith("classes") and i.filename.endswith(".dex"):
|
|
data = z.read(i.filename)
|
|
if b"UpdateInstaller" in data and b"yama_update" in data:
|
|
dex_ok = True
|
|
check(dex_ok, "dex has UpdateInstaller (this build can be upgraded later)")
|
|
|
|
markers = list(MARKERS)
|
|
if arg("--marker"):
|
|
markers.insert(0, arg("--marker").encode() + b"\x00")
|
|
flag_needle = None
|
|
admin_needle = None
|
|
if want_admin:
|
|
admin_needle = struct.pack("<Q", int(want_admin, 16))
|
|
# BuildDlg rewrites szFlag to the first 16 chars of the master id, which is
|
|
# the same hex string the admin id was parsed from.
|
|
flag_needle = want_admin[:16].encode()
|
|
|
|
def raw_fields(base):
|
|
ip = bytes(data[base + OFF_IP:base + OFF_IP + LEN_IP])
|
|
pt = bytes(data[base + OFF_PORT:base + OFF_PORT + LEN_PORT])
|
|
return ip, pt
|
|
|
|
def decrypted(base):
|
|
ip, pt = raw_fields(base)
|
|
if data[base + OFF_ENCRYPT]:
|
|
plain = stream_cipher(ip + pt)
|
|
ip, pt = plain[:LEN_IP], plain[LEN_IP:]
|
|
return ip.split(b"\0")[0], pt.split(b"\0")[0]
|
|
|
|
def sane(ip, pt):
|
|
return (ip and all(48 <= c <= 57 or c == 46 for c in ip) and
|
|
pt and all(48 <= c <= 57 for c in pt))
|
|
|
|
def valid_struct(base):
|
|
if base < 0 or base + OFF_ADMIN + 8 > len(data):
|
|
return False
|
|
itype = struct.unpack_from("<i", data, base + OFF_TYPE)[0]
|
|
enc = data[base + OFF_ENCRYPT]
|
|
if itype != CLIENT_TYPE_ANDROID or enc not in (0, 1):
|
|
return False
|
|
return sane(*decrypted(base))
|
|
|
|
def find_struct(d):
|
|
for m in markers:
|
|
start = 0
|
|
while True:
|
|
p = d.find(m, start)
|
|
if p < 0:
|
|
break
|
|
# pristine template: szFlag plaintext, IP not yet encrypted
|
|
if d[p + OFF_ENCRYPT] == 0 and sane(*raw_fields(p)):
|
|
return p
|
|
start = p + 1
|
|
if flag_needle:
|
|
start = 0
|
|
while True:
|
|
p = d.find(flag_needle, start)
|
|
if p < 0:
|
|
break
|
|
if valid_struct(p):
|
|
return p
|
|
start = p + 1
|
|
if admin_needle:
|
|
start = 0
|
|
while True:
|
|
p = d.find(admin_needle, start)
|
|
if p < 0:
|
|
break
|
|
base = p - OFF_ADMIN
|
|
if valid_struct(base):
|
|
return base
|
|
start = p + 1
|
|
if want_ip: # last resort: plaintext IP string
|
|
start = 0
|
|
while True:
|
|
p = d.find(want_ip.encode(), start)
|
|
if p < 0:
|
|
break
|
|
base = p - OFF_IP
|
|
if base >= 0 and valid_struct(base):
|
|
return base
|
|
start = p + 1
|
|
return -1
|
|
|
|
for i in sos:
|
|
check(i.compress_type == 0, "%s stored (not deflated)" % i.filename)
|
|
data, crc_ok = read_entry(i.filename)
|
|
if not crc_ok:
|
|
print(" WARN %s: ZIP CRC is stale (patched in place, as BuildDlg does) - "
|
|
"harmless for install, but the APK must be re-signed" % i.filename)
|
|
pos = find_struct(data)
|
|
abi = i.filename.split("/")[1]
|
|
if pos < 0:
|
|
check(False, "%s: CONNECT_ADDRESS not found" % i.filename)
|
|
continue
|
|
ip, port = decrypted(pos)
|
|
ip_s, port_s = ip.decode("latin1"), port.decode("latin1")
|
|
enc = data[pos + OFF_ENCRYPT]
|
|
admin = struct.unpack_from("<Q", data, pos + OFF_ADMIN)[0]
|
|
print(" %-12s ip=%s port=%s admin=%016x enc=%d" % (abi, ip_s, port_s, admin, enc))
|
|
if admin == 0:
|
|
print(" WARN admin=0: the server's update dialog will say it cannot find "
|
|
"this master's id and offer 'send anyway'")
|
|
if want_ip:
|
|
check(ip_s == want_ip, "%s: ip %s == %s" % (abi, ip_s, want_ip))
|
|
if want_port:
|
|
check(port_s == want_port, "%s: port %s == %s" % (abi, port_s, want_port))
|
|
if want_admin:
|
|
check(admin == int(want_admin, 16),
|
|
"%s: admin %016x == %s" % (abi, admin, want_admin))
|
|
|
|
aapt = None
|
|
if sdk:
|
|
cands = sorted(glob.glob(os.path.join(sdk, "build-tools", "*", "aapt2.exe"))) or \
|
|
sorted(glob.glob(os.path.join(sdk, "build-tools", "*", "aapt2")))
|
|
aapt = cands[-1] if cands else None
|
|
if aapt:
|
|
out = subprocess.run([aapt, "dump", "badging", apk], capture_output=True, text=True).stdout
|
|
m = re.search(r"package: name='([^']+)' versionCode='(\d+)' versionName='([^']*)'", out)
|
|
if m:
|
|
print(" package=%s versionCode=%s versionName=%s" % (m.group(1), m.group(2), m.group(3)))
|
|
check(m.group(1) == "com.yama.client", "package is com.yama.client")
|
|
m = re.search(r"native-code: (.*)", out)
|
|
if m:
|
|
print(" native-code: %s" % m.group(1))
|
|
|
|
if want_cert:
|
|
print(" (check the cert with apksigner verify --print-certs; expected %s)" % want_cert)
|
|
|
|
print()
|
|
if fails:
|
|
print("RESULT: %d check(s) failed - do not send this APK" % len(fails))
|
|
return 1
|
|
print("RESULT: passed")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|