static_analysis.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. # -*- coding: utf-8 -*-
  2. """纯静态内存分析:从 zip 直接读取 exe 字节做 PE/字符串/行为特征分析,不落地、不执行。"""
  3. import glob
  4. import hashlib
  5. import re
  6. import struct
  7. import sys
  8. import zipfile
  9. import zlib
  10. import pefile
  11. sys.stdout.reconfigure(encoding='utf-8', errors='replace')
  12. # ---------- 1. 从 zip 内存中读取 exe ----------
  13. zip_path = next(z for z in glob.glob(r'C:/Users/20175/Downloads/*.zip')
  14. if '3.24' in z.lower() or 'BBA' in z.lower())
  15. zf = zipfile.ZipFile(zip_path)
  16. exe_name = None
  17. for n in zf.namelist():
  18. if n.lower().endswith('.exe'):
  19. exe_name = n # 取最后一个 .exe,主程序按体积最大再校验
  20. data = zf.read(exe_name)
  21. print(f'来源: {zip_path} -> {exe_name}')
  22. print(f'大小: {len(data):,} bytes')
  23. print(f'MD5 : {hashlib.md5(data).hexdigest()}')
  24. print(f'SHA256: {hashlib.sha256(data).hexdigest()}')
  25. # ---------- 2. PE 结构 ----------
  26. pe = pefile.PE(data=data)
  27. print('\n=== PE 段表(熵>7.2 通常意味着加壳/加密) ===')
  28. for s in pe.sections:
  29. name = s.Name.decode(errors='ignore').strip('\x00')
  30. print(f' {name:<10} raw={s.SizeOfRawData:>10,} entropy={s.get_entropy():.2f}')
  31. print('\n=== 导入表与可疑 API ===')
  32. all_imports = []
  33. if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):
  34. for entry in pe.DIRECTORY_ENTRY_IMPORT:
  35. dll = entry.dll.decode(errors='ignore')
  36. funcs = [imp.name.decode(errors='ignore') for imp in entry.imports if imp.name]
  37. all_imports += funcs
  38. hot = [f for f in funcs if re.search(
  39. r'Crypt|Http|Internet|Url|Socket|Hook|VirtualAlloc|WriteProcessMemory|'
  40. r'CreateProcess|ShellExecute|WinExec|RegSet|Connect|Send|Recv|Track', f, re.I)]
  41. if hot:
  42. print(f' [{dll}] 可疑: {", ".join(hot[:12])}')
  43. # ---------- 3. 字符串提取(ASCII / UTF-16 / GBK中文) ----------
  44. def extract_urls(strs):
  45. found = set()
  46. for s in strs:
  47. for m in re.findall(r'https?://[^\s"\'<>{}|\\^`\[\]]+', s):
  48. found.add(m.rstrip(').,;'))
  49. for m in re.findall(r'\b(?:[a-z0-9-]+\.)+(?:com|cn|net|top|xyz|vip|icu|cc|shop|fun|site|online|club|link|me|io)(?::\d+)?\b',
  50. s, re.I):
  51. found.add(m.lower())
  52. return sorted(found)
  53. A = [m.decode('ascii') for m in re.findall(rb'[\x20-\x7e]{6,}', data)]
  54. U = [m.decode('utf-16-le', errors='ignore')
  55. for m in re.findall(rb'(?:[\x20-\x7e]\x00){6,}', data)]
  56. G = []
  57. for m in re.findall(rb'(?:[\x20-\x7e\xa1-\xfe]{6,})', data):
  58. try:
  59. s = m.decode('gbk')
  60. if any('\u4e00' <= c <= '\u9fff' for c in s):
  61. G.append(s)
  62. except Exception:
  63. pass
  64. ALL = A + U + G
  65. print(f'\n=== 字符串统计: ASCII {len(A)} | UTF16 {len(U)} | GBK中文 {len(G)} ===')
  66. # ---------- 4. 框架识别 ----------
  67. print('\n=== 打包/框架特征 ===')
  68. flat = '\n'.join(ALL)
  69. for label, pats in {
  70. 'PyInstaller': [r'MEI\\x0c', r'pyi-', r'PyInstaller', r'python3\d'],
  71. '.NET': [r'mscoree\.dll', r'GetRuntimeInterfaceMapOffset'],
  72. '易语言': [r'krnln', r'e\.fnr', r'EPL'],
  73. 'aardio': [r'aardio'],
  74. 'AutoIt': [r'AutoIt', r'AU3!'],
  75. 'Delphi/C++Builder': [r'TForm', r'Borland', r'Embarcadero'],
  76. 'Electron/CEF': [r'app\.asar', r'CefSharp', r'libcef'],
  77. 'UPX壳': [r'UPX0', r'UPX1', r'UPX!'],
  78. }.items():
  79. hits = [p for p in pats if re.search(p, flat)]
  80. if hits:
  81. print(f' {label}: 命中 {hits}')
  82. # ---------- 5. 网络地址 ----------
  83. urls = extract_urls(A + U)
  84. print(f'\n=== URL/域名({len(urls)}) ===')
  85. for u in urls[:60]:
  86. print(f' {u}')
  87. # ---------- 6. 敏感行为路径 ----------
  88. print('\n=== 敏感路径/关键词命中 ===')
  89. KEYS = ['User Data', 'Cookies', 'Login Data', 'Local State', 'AppData',
  90. 'Chrome', 'Edge', 'Firefox', 'MetaMask', 'TronLink', 'wallet',
  91. 'Telegram', 'WeChat', 'wechat', 'wxid', 'keystone', 'password',
  92. 'passwd', '2fa', 'authenticator', 'screenshot', 'keylog', 'clipboard',
  93. 'kuaishou', 'douyin', 'passport', 'token', 'cookie']
  94. seen = set()
  95. for k in KEYS:
  96. hits = sorted({s.strip() for s in ALL if k in s and len(s) < 120})[:4]
  97. for h in hits:
  98. key = (k, h[:90])
  99. if key not in seen:
  100. seen.add(key)
  101. print(f' [{k}] {h[:110]}')
  102. # ---------- 7. PyInstaller 内部模块清单(若命中) ----------
  103. MAGIC = b'MEI\x0c\x0b\x0a\x0b\x0e'
  104. pos = data.rfind(MAGIC)
  105. if pos != -1:
  106. print(f'\n=== PyInstaller CArchive 命中 @{pos} ===')
  107. # cookie 结构: magic(8) + pkgLen(I) + toc(I) + tocLen(I) + pyver(i) + pylibname(64s, 仅新版)
  108. tail = data[pos:pos + 88]
  109. magic, pkg_len, toc_off, toc_len, pyver = struct.unpack('!8sIIIi', tail[:24])
  110. toc_abs = pos - pkg_len + toc_off # CArchive 起始 = cookie位置+24(or 88) - pkgLen
  111. toc = data[toc_abs:toc_abs + toc_len]
  112. entries, i = [], 0
  113. while i < len(toc):
  114. entry_size, = struct.unpack('!I', toc[i:i + 4])
  115. if entry_size == 0:
  116. break
  117. epos, clen, ulen, flag, ctype = struct.unpack('!IIIBc', toc[i + 4:i + 18])
  118. name = toc[i + 18:i + entry_size].rstrip(b'\x00').decode('utf-8', 'replace')
  119. entries.append((name, ctype.decode(), toc_abs_base := (pos + 24 - pkg_len) + epos, clen, ulen, flag))
  120. i += entry_size
  121. print(f' 内部条目 {len(entries)} 个, Python {pyver}')
  122. names = [e[0] for e in entries]
  123. for n in names[:80]:
  124. print(f' {n}')
  125. # 解压模块并抽字符串(仅看结构,不执行)
  126. print('\n=== 模块内容抽样字符串 ===')
  127. shown = 0
  128. for name, ctype, epos, clen, ulen, flag in entries:
  129. if shown >= 12:
  130. break
  131. if ctype in ('s', 'm', 'M') and clen < 3_000_000:
  132. try:
  133. raw = zlib.decompress(data[epos:epos + clen]) if flag else data[epos:epos + clen]
  134. strs = [m.decode('utf-8', 'replace') for m in re.findall(rb'[\x20-\x7e\xe4-\xe9][\x20-\x7e\x80-\xff]{8,}', raw)][:6]
  135. urls_m = extract_urls(strs)
  136. keep = [s for s in strs if any(k in s for k in ('http', '.com', '.cn', 'cookie', 'Cookie',
  137. 'token', 'upload', 'api', 'user', 'pass', '登录', '账号', '发布', '快手', '抖音'))]
  138. if keep:
  139. print(f' [{name}]')
  140. for s in keep[:6]:
  141. print(f' {s[:100]}')
  142. shown += 1
  143. except Exception:
  144. pass
  145. else:
  146. print('\n(未发现 PyInstaller CArchive 标记)')