Files
pinhaofan/AI代码/解密mtgsig.py
T
2026-11-11 22:25:40 +08:00

238 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 解析一份 mtgsig:把 a6/a5/a4 里的身份、设备画像、检测点全部解出来(自用,不依赖出签服务)
#
# 用法:把 __main__ 里的 text 换成要解的 mtgsig(本体,或含 "mtgsig" 字段的整段抓包 JSON),
# 直接 python 解密mtgsig.py,结果打印并写成 mtgsig解密值.json
#
# 返回/打印一个 dict:身份(a6) / 出签上下文(a5 的 qn) / 检测点(防篡改位图 r、开关位、ext、gzip 头…)
import base64
import hashlib
import json
import os
import sys
import zlib
from binascii import hexlify
import newsetting as ten
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='headers_project')
from Crypto.Cipher import AES
def get_header_rows():
"""取未处理的模板包(id / json_data / current_count)"""
sql = f'''
select id, json_data, current_count from waima_coupon_list_headers where id = {id_}
'''
rows = tent.get_shoppingmalls(sql)
print('未处理模板包 %d 条' % len(rows))
return rows
A6_KEY = b'z7Jut6Ywr2Pe5Nhx'
A6_IV = b'0807060504030201'
A5_ALPHA = 'ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5'
# a6 里 system 数组的 46 项顺序(= jsguard 的 vt.system)
SYSTEM_FIELDS = [
'accelerometer', 'albumAuthorized', 'BatteryInfo', 'batteryLevel', 'Beacons', 'benchmarkLevel',
'bluetoothEnabled', 'brand', 'brightness', 'cameraAuthorized', 'compass', 'deviceOrientation',
'devicePixelRatio', 'enableDebug', 'errMsg', 'fontSizeSetting', 'language', 'LaunchOptionsSync',
'locationAuthorized', 'locationEnabled', 'locationReducedAccuracy', 'microphoneAuthorized', 'model',
'networkType', 'notificationAlertAuthorized', 'notificationAuthorized', 'notificationBadgeAuthorized',
'notificationSoundAuthorized', 'pixelRatio', 'platform', 'safeArea', 'screenHeight', 'screenTop',
'screenWidth', 'SDKVersion', 'statusBarHeight', 'system', 'version', 'wifiEnabled', 'WifiInfo',
'windowHeight', 'windowWidth', 'screenRecord', 'isPrivacy', 'hasSystemProxy', 'captureRecord',
]
# a6 里 ext 数组的 5 项
EXT_FIELDS = ['NativeClient存在', 'addEventListener存在', 'getPublicLibVersion(1一致/0不一致/2空对象)',
'__WeixinJSBridge存在', 'NFC(1成功/2未开/3无NFC/4canIUse假)']
# a5 里 qn 的含义
QN_FIELDS = {
'b1': 'getAccountInfoSync(含小程序版本)',
'b2': '当前路由 getCurrentPages().route',
'b6': 'openId(账号身份)',
'b7': '会话起始秒(init 时写入)',
'b8': '出签序号(同一实例自增)',
'b9': '开关位图 En.join(真机健康值 22122)',
'b10': '失败上报数组(有才出现)',
'b11': '定位精度串 accuracy_hacc_vacc',
'b12': 'appid',
}
A6_FIELDS = ['app(appid)', 'dfpid', 'filetime(USER_DATA_PATH 最后修改ms)', 'fpv(jsguard版本)',
'localid(时间戳+7随机大写+md5)', 'system(46项设备画像)', 'timestamp(秒)',
'ext(5项能力探测)', 'sessionId']
def b64_alpha(s):
"""a5 用的自定义字母表 base64 解码(= 号直接跳过)"""
buf = 0
nb = 0
out = bytearray()
for ch in s:
v = A5_ALPHA.find(ch)
if v < 0:
continue
buf = (buf << 6) | v
nb += 6
if nb >= 8:
nb -= 8
out.append((buf >> nb) & 0xFF)
return bytes(out)
def rc4_twist(key, data):
"""与 jsguard 一致的 RC4 变体(KSA 里多加了 +31)"""
s = list(range(256))
j = 0
for i in range(256):
j = (j + s[i] + key[i % len(key)] + 31) % 256
s[i], s[j] = s[j], s[i]
out = bytearray()
i = j = 0
for ch in data:
i = (i + 1) % 256
j = (j + s[i]) % 256
s[i], s[j] = s[j], s[i]
out.append(ch ^ s[(s[i] + s[j]) % 256])
return bytes(out)
def crc32_twist(b):
"""jsguard 的 crc32 变体:反射多项式 0xEDB88320、初值全 1、末异或 306674911(=0x12477CDF,不是标准的 0xFFFFFFFF)"""
crc = 0xFFFFFFFF
for ch in b:
crc ^= ch
for _ in range(8):
crc = (crc >> 1) ^ (0xEDB88320 if crc & 1 else 0)
return (crc ^ 306674911) & 0xFFFFFFFF
def aes_cbc_dec(data):
return AES.new(A6_KEY, AES.MODE_CBC, A6_IV).decrypt(data)
def gunzip(data):
"""只解第一个 gzip 成员:AES 解出来的尾部是填充字节,gzip.decompress 会把它当成第二个成员而报错"""
return zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(data)
def parse_a6(a6):
"""解 a6 -> 9 项数组 + gzip 头"""
if not str(a6).startswith('w1.'):
raise ValueError('a6 前缀是 %r,不是小程序 jsguard(w1.x);H5 的 mtgsig(h1.9/hs1.6) 本脚本解不了' % str(a6)[:4])
raw = aes_cbc_dec(base64.b64decode(a6[4:]))
arr = json.loads(gunzip(raw).decode('utf-8'))
system = {}
for i, name in enumerate(SYSTEM_FIELDS):
v = arr[5][i] if i < len(arr[5]) else None
if name in ('LaunchOptionsSync', 'StorageInfo') and isinstance(v, str) and v.startswith('{'):
try:
v = json.loads(v) # 原来是 JSON 串,解出来更好看
except Exception:
pass
system[name] = v
ext = {}
for i, name in enumerate(EXT_FIELDS):
ext[name] = arr[7][i] if i < len(arr[7]) else None
out = {
'gzip头': {'mtime': int.from_bytes(raw[4:8], 'little'), 'os': raw[9]},
'system': system,
'ext': ext,
}
for i, name in enumerate(A6_FIELDS):
if name.startswith('system') or name.startswith('ext'):
continue
out[name] = arr[i]
return out
def parse_a5(a5, a2, a6):
"""解 a5 -> y(16B) 结构 + qn;并回算防篡改位图 r"""
w = b64_alpha(a5)
y, ct = w[:16], w[16:]
qn = json.loads(rc4_twist(y, ct).decode('utf-8'))
l = (a2 & 0xFFFFFFFF).to_bytes(4, 'big')
checks = {
'r(防篡改位图)': y[7] ^ (crc32_twist(l) & 0xFF), # 真机 appservice = 1
'y[0:7]==md5(a6)前7字节': hexlify(y[:7]).decode() ==
hashlib.md5(a6.encode('utf-8') + l).hexdigest()[:14],
'y[8:12]==a2低32位': int.from_bytes(y[8:12], 'big') == (a2 & 0xFFFFFFFF),
'y[12:16]==crc32(y前12字节)': int.from_bytes(y[12:16], 'big') == crc32_twist(y[:12]),
}
qn_named = {}
for k, v in qn.items():
qn_named[k] = {'值': v, '含义': QN_FIELDS.get(k, '?')}
return {'qn': qn_named, '自查': checks}
def parse_a4(a4):
"""解 a4:拆成 x / _ 及两个 XOR 项,验证结构"""
b = bytes.fromhex(a4)
x = int.from_bytes(b[0:4], 'big')
under = int.from_bytes(b[4:8], 'big')
low = int.from_bytes(b[16:20], 'little') ^ x # = a2 低32位
return {
'x=murmur3(方法+路径+query+body)': hex(x),
'_=murmur3(a5字符串)': hex(under),
'a2低32位(=x^此行)': hex(low),
'结构自校验': {
'b[8:12]==LE32(x)': int.from_bytes(b[8:12], 'little') == x,
'b[12:16]==LE32(_)': int.from_bytes(b[12:16], 'little') == under,
'b[16:20]==LE32(x^a2低32)': int.from_bytes(b[16:20], 'little') == (x ^ low),
'b[20:24]==LE32(x^_^a2低32)': int.from_bytes(b[20:24], 'little') == (x ^ under ^ low),
},
}
def parse_mtgsig(mtgsig):
"""入口:传 mtgsig 的 JSON 字符串,返回 dict"""
if isinstance(mtgsig, str):
mtgsig = json.loads(mtgsig)
a2 = mtgsig['a2']
out = {
'字段': dict(mtgsig), # a1 a2 a3 a4 a5 a6 a7 x0 d1 原样留一份
'a2时间': a2 / 1000,
}
try:
out['a6身份'] = parse_a6(mtgsig['a6'])
except Exception as e:
out['a6身份'] = '解失败: %s' % e
try:
out['a5上下文'] = parse_a5(mtgsig['a5'], a2, mtgsig['a6'])
except Exception as e:
out['a5上下文'] = '解失败: %s' % e
try:
out['a4结构'] = parse_a4(mtgsig['a4'])
except Exception as e:
out['a4结构'] = '解失败: %s' % e
return out
def _pick_mtgsig(raw):
"""从输入里抠出 mtgsig:本体 / 含 mtgsig 字段的抓包 JSON / 文件路径"""
raw = raw.strip()
if os.path.exists(raw):
raw = open(raw, encoding='utf-8').read().strip()
try:
obj = json.loads(raw)
except Exception:
return raw # 不是 JSON,当成本体
if isinstance(obj, dict):
if 'mtgsig' in obj:
return json.dumps(obj['mtgsig']) if not isinstance(obj['mtgsig'], str) else obj['mtgsig']
if 'headers' in obj and 'mtgsig' in obj['headers']: # 整段抓包
return obj['headers']['mtgsig']
return raw
if __name__ == '__main__':
id_=13
header_rows = get_header_rows()
text = header_rows[0][1]
text = '{"a1":"1.2","a2":1793339512511,"a3":"9v67307y25u85358y1y9zw93669w76vu8z818043u9377978462uwxz6","a4":"d3cb59dd6f1ca0b8dd59cbd3b8a01c6f620f9658daaf8a37","a5":"JSfkf+wH8axNgpy524MuRpn1YY4wB16sY3q+zxcAxMcnlHaW4d6H/s2NYVjofHAkOxoaPyBeMFvo5fF9wCb1d+Q8yCBYkPo3m/Q+tkqJp5OERZCXFqeG4iqkziDbo7UFrlxNFnX5VcTU6qqv6xruWt2XARJw6lVq9Zqrai2JYSpQFnbHg06rRF3Aa/ucyKptCZF+zfAevB0pyW44jNE1l4kGbpvqYNFQ+Tho3UvojSc0E1biIbQxoEbSG9/YF+jqyvlM2K9ABJkFgBlK2haybq82w42IRPH9h9vo+5ihfeEcU83YemzW8rMHjnIUY/OWTmb0l5c=","a6":"w1.6M5eQZ6Ej+qKlesiYotUiKjLSRSjW/jYxgb6YW6ckYKjkB+guB2tfhO7tS/PVKwzzvN6EMZnC71R7ypLdUSOEqZdbNQmVdeS4kc/Z2HKzhsOwHCQFw5TxvBuS9d3BRpRpZSwxYMVeAUy2NsCu+c6u4YFdlpZZ/3kxquhOSo4IZ4zZtFaBeEzbXPgJAIt82lWfs6ns2Lq1PjZ6WD7ndR/zvxLQBYw3NLDWZdS6yFlS0z3/ayZUVu/M9/R0ggltty+ort7Jti6Dj4AGel/W82QqX+FPu5o7/gFwc2jYl1mPbc2ZJU/dXf6Ie0oF3gIMon2ePrhalxHCPu6014wQB2gnATYTt1zcukw2a7+irCm43ROmXxNQHrLNMyuyfAlpULSPMps8rPIXV2kcF9K87sWMFISDARxoulGWWlY0zAuBGoL9Xp28MccUGCNjZr+Y0G0Pzw2WVKxvVWyacnyhrKsP1XHiZiMLnVYCspQh+Isci0+7YPopRuUJEQwiGoteQHyd3Glge0RoMb7An5o1dQLImEOyceWaAOYj9Cio5HjJeXR/7MrCwCTPDyMeyUi4oPwYTk+NPz/TRHj418F4fBp+5eVoY16yf7Zst3tfMr+6RIqdBZzNXrqjN6xoyx2dJGRqlxymbE5iZK/G1L5K2r+8DRI+Xl1B8cYhMkrbbBYcYxo6U9ZXBDsLxpgKmdHohrVp","a7":"wx92916b3adca84096","x0":3,"d1":"57e575c90db882ff7bf097966ab4e7f1"}'
# input(645)
# with open(r'C:\Users\mjz\Desktop\python\10月\店铺详情\mtgsig.txt','r',encoding='utf-8') as f:
# text = f.read()
result = parse_mtgsig(_pick_mtgsig(text))
out = json.dumps(result, ensure_ascii=False, indent=2)
with open('mtgsig解密值.json', 'w', encoding='utf-8') as f:
f.write(out)
print(out)