emulator_windows.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. import codecs
  2. import os
  3. import re
  4. import typing as t
  5. import winreg
  6. from dataclasses import dataclass
  7. # module/device/platform/emulator_base.py
  8. # module/device/platform/emulator_windows.py
  9. # Will be used in Alas Easy Install, they shouldn't import any Alas modules.
  10. from module.device.platform2.emulator_base import (
  11. EmulatorBase,
  12. EmulatorInstanceBase,
  13. EmulatorManagerBase,
  14. remove_duplicated_path)
  15. from module.device.platform2.utils import cached_property, iter_folder
  16. @dataclass
  17. class RegValue:
  18. name: str
  19. value: str
  20. typ: int
  21. def list_reg(reg) -> t.List[RegValue]:
  22. """
  23. List all values in a reg key
  24. """
  25. rows = []
  26. index = 0
  27. try:
  28. while 1:
  29. value = RegValue(*winreg.EnumValue(reg, index))
  30. index += 1
  31. rows.append(value)
  32. except OSError:
  33. pass
  34. return rows
  35. def list_key(reg) -> t.List[RegValue]:
  36. """
  37. List all values in a reg key
  38. """
  39. rows = []
  40. index = 0
  41. try:
  42. while 1:
  43. value = winreg.EnumKey(reg, index)
  44. index += 1
  45. rows.append(value)
  46. except OSError:
  47. pass
  48. return rows
  49. def abspath(path):
  50. return os.path.abspath(path).replace('\\', '/')
  51. class EmulatorInstance(EmulatorInstanceBase):
  52. @cached_property
  53. def emulator(self):
  54. """
  55. Returns:
  56. Emulator:
  57. """
  58. return Emulator(self.path)
  59. class Emulator(EmulatorBase):
  60. @classmethod
  61. def path_to_type(cls, path: str) -> str:
  62. """
  63. Args:
  64. path: Path to .exe file, case insensitive
  65. Returns:
  66. str: Emulator type, such as Emulator.NoxPlayer
  67. """
  68. folder, exe = os.path.split(path)
  69. folder, dir1 = os.path.split(folder)
  70. folder, dir2 = os.path.split(folder)
  71. exe = exe.lower()
  72. dir1 = dir1.lower()
  73. dir2 = dir2.lower()
  74. if exe == 'nox.exe':
  75. if dir2 == 'nox':
  76. return cls.NoxPlayer
  77. elif dir2 == 'nox64':
  78. return cls.NoxPlayer64
  79. else:
  80. return cls.NoxPlayer
  81. if exe == 'bluestacks.exe':
  82. if dir1 in ['bluestacks', 'bluestacks_cn']:
  83. return cls.BlueStacks4
  84. elif dir1 in ['bluestacks_nxt', 'bluestacks_nxt_cn']:
  85. return cls.BlueStacks5
  86. else:
  87. return cls.BlueStacks4
  88. if exe == 'hd-player.exe':
  89. if dir1 in ['bluestacks', 'bluestacks_cn']:
  90. return cls.BlueStacks4
  91. elif dir1 in ['bluestacks_nxt', 'bluestacks_nxt_cn']:
  92. return cls.BlueStacks5
  93. else:
  94. return cls.BlueStacks5
  95. if exe == 'dnplayer.exe':
  96. if dir1 == 'ldplayer':
  97. return cls.LDPlayer3
  98. elif dir1 == 'ldplayer4':
  99. return cls.LDPlayer4
  100. elif dir1 == 'ldplayer9':
  101. return cls.LDPlayer9
  102. else:
  103. return cls.LDPlayer3
  104. if exe == 'nemuplayer.exe':
  105. if dir2 == 'nemu':
  106. return cls.MuMuPlayer
  107. elif dir2 == 'nemu9':
  108. return cls.MuMuPlayerX
  109. else:
  110. return cls.MuMuPlayer
  111. if exe == 'mumuplayer.exe':
  112. return cls.MuMuPlayer12
  113. if exe == 'memu.exe':
  114. return cls.MEmuPlayer
  115. return ''
  116. @staticmethod
  117. def multi_to_single(exe):
  118. """
  119. Convert a string that might be a multi-instance manager to its single instance executable.
  120. Args:
  121. exe (str): Path to emulator executable
  122. Yields:
  123. str: Path to emulator executable
  124. """
  125. if 'HD-MultiInstanceManager.exe' in exe:
  126. yield exe.replace('HD-MultiInstanceManager.exe', 'HD-Player.exe')
  127. yield exe.replace('HD-MultiInstanceManager.exe', 'Bluestacks.exe')
  128. elif 'MultiPlayerManager.exe' in exe:
  129. yield exe.replace('MultiPlayerManager.exe', 'Nox.exe')
  130. elif 'dnmultiplayer.exe' in exe:
  131. yield exe.replace('dnmultiplayer.exe', 'dnplayer.exe')
  132. elif 'NemuMultiPlayer.exe' in exe:
  133. yield exe.replace('NemuMultiPlayer.exe', 'NemuPlayer.exe')
  134. elif 'MuMuMultiPlayer.exe' in exe:
  135. yield exe.replace('MuMuMultiPlayer.exe', 'MuMuPlayer.exe')
  136. elif 'MuMuManager.exe' in exe:
  137. yield exe.replace('MuMuManager.exe', 'MuMuPlayer.exe')
  138. elif 'MEmuConsole.exe' in exe:
  139. yield exe.replace('MEmuConsole.exe', 'MEmu.exe')
  140. else:
  141. yield exe
  142. @staticmethod
  143. def single_to_console(exe: str):
  144. """
  145. Convert a string that might be a single instance executable to its console.
  146. Args:
  147. exe (str): Path to emulator executable
  148. Returns:
  149. str: Path to emulator console
  150. """
  151. if 'MuMuPlayer.exe' in exe:
  152. return exe.replace('MuMuPlayer.exe', 'MuMuManager.exe')
  153. elif 'LDPlayer.exe' in exe:
  154. return exe.replace('LDPlayer.exe', 'ldconsole.exe')
  155. elif 'dnplayer.exe' in exe:
  156. return exe.replace('dnplayer.exe', 'ldconsole.exe')
  157. elif 'Bluestacks.exe' in exe:
  158. return exe.replace('Bluestacks.exe', 'bsconsole.exe')
  159. elif 'MEmu.exe' in exe:
  160. return exe.replace('MEmu.exe', 'memuc.exe')
  161. else:
  162. return exe
  163. @staticmethod
  164. def vbox_file_to_serial(file: str) -> str:
  165. """
  166. Args:
  167. file: Path to vbox file
  168. Returns:
  169. str: serial such as `127.0.0.1:5555`
  170. """
  171. regex = re.compile('<*?hostport="(.*?)".*?guestport="5555"/>')
  172. try:
  173. with open(file, 'r', encoding='utf-8', errors='ignore') as f:
  174. for line in f.readlines():
  175. # <Forwarding name="port2" proto="1" hostip="127.0.0.1" hostport="62026" guestport="5555"/>
  176. res = regex.search(line)
  177. if res:
  178. return f'127.0.0.1:{res.group(1)}'
  179. return ''
  180. except FileNotFoundError:
  181. return ''
  182. def iter_instances(self):
  183. """
  184. Yields:
  185. EmulatorInstance: Emulator instances found in this emulator
  186. """
  187. if self == Emulator.NoxPlayerFamily:
  188. # ./BignoxVMS/{name}/{name}.vbox
  189. for folder in self.list_folder('./BignoxVMS', is_dir=True):
  190. for file in iter_folder(folder, ext='.vbox'):
  191. serial = Emulator.vbox_file_to_serial(file)
  192. if serial:
  193. yield EmulatorInstance(
  194. serial=serial,
  195. name=os.path.basename(folder),
  196. path=self.path,
  197. )
  198. elif self == Emulator.BlueStacks5:
  199. # Get UserDefinedDir, where BlueStacks stores data
  200. folder = None
  201. try:
  202. with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt") as reg:
  203. folder = winreg.QueryValueEx(reg, 'UserDefinedDir')[0]
  204. except FileNotFoundError:
  205. pass
  206. try:
  207. with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt_cn") as reg:
  208. folder = winreg.QueryValueEx(reg, 'UserDefinedDir')[0]
  209. except FileNotFoundError:
  210. pass
  211. if not folder:
  212. return
  213. # Read {UserDefinedDir}/bluestacks.conf
  214. try:
  215. with open(self.abspath('./bluestacks.conf', folder), encoding='utf-8') as f:
  216. content = f.read()
  217. except FileNotFoundError:
  218. return
  219. # bst.instance.Nougat64.adb_port="5555"
  220. emulators = re.findall(r'bst.instance.(\w+).status.adb_port="(\d+)"', content)
  221. for emulator in emulators:
  222. yield EmulatorInstance(
  223. serial=f'127.0.0.1:{emulator[1]}',
  224. name=emulator[0],
  225. path=self.path,
  226. )
  227. elif self == Emulator.BlueStacks4:
  228. # ../Engine/Android
  229. regex = re.compile(r'^Android')
  230. for folder in self.list_folder('../Engine', is_dir=True):
  231. folder = os.path.basename(folder)
  232. res = regex.match(folder)
  233. if not res:
  234. continue
  235. # Serial from BlueStacks4 are not static, they get increased on every emulator launch
  236. # Assume all use 127.0.0.1:5555
  237. yield EmulatorInstance(
  238. serial=f'127.0.0.1:5555',
  239. name=folder,
  240. path=self.path
  241. )
  242. elif self == Emulator.LDPlayerFamily:
  243. # ./vms/leidian0
  244. regex = re.compile(r'^leidian(\d+)$')
  245. for folder in self.list_folder('./vms', is_dir=True):
  246. folder = os.path.basename(folder)
  247. res = regex.match(folder)
  248. if not res:
  249. continue
  250. # LDPlayer has no forward port config in .vbox file
  251. # Ports are auto increase, 5555, 5557, 5559, etc
  252. port = int(res.group(1)) * 2 + 5555
  253. yield EmulatorInstance(
  254. serial=f'127.0.0.1:{port}',
  255. name=folder,
  256. path=self.path
  257. )
  258. elif self == Emulator.MuMuPlayer:
  259. # MuMu has no multi instances, on 7555 only
  260. yield EmulatorInstance(
  261. serial='127.0.0.1:7555',
  262. name='',
  263. path=self.path,
  264. )
  265. elif self == Emulator.MuMuPlayerX:
  266. # vms/nemu-12.0-x64-default
  267. for folder in self.list_folder('../vms', is_dir=True):
  268. for file in iter_folder(folder, ext='.nemu'):
  269. serial = Emulator.vbox_file_to_serial(file)
  270. if serial:
  271. yield EmulatorInstance(
  272. serial=serial,
  273. name=os.path.basename(folder),
  274. path=self.path,
  275. )
  276. elif self == Emulator.MuMuPlayer12:
  277. # vms/MuMuPlayer-12.0-0
  278. for folder in self.list_folder('../vms', is_dir=True):
  279. for file in iter_folder(folder, ext='.nemu'):
  280. serial = Emulator.vbox_file_to_serial(file)
  281. name = os.path.basename(folder)
  282. if serial:
  283. yield EmulatorInstance(
  284. serial=serial,
  285. name=name,
  286. path=self.path,
  287. )
  288. # Fix for MuMu12 v4.0.4, default instance of which has no forward record in vbox config
  289. else:
  290. instance = EmulatorInstance(
  291. serial=serial,
  292. name=name,
  293. path=self.path,
  294. )
  295. if instance.MuMuPlayer12_id:
  296. instance.serial = f'127.0.0.1:{16384 + 32 * instance.MuMuPlayer12_id}'
  297. yield instance
  298. elif self == Emulator.MEmuPlayer:
  299. # ./MemuHyperv VMs/{name}/{name}.memu
  300. for folder in self.list_folder('./MemuHyperv VMs', is_dir=True):
  301. for file in iter_folder(folder, ext='.memu'):
  302. serial = Emulator.vbox_file_to_serial(file)
  303. if serial:
  304. yield EmulatorInstance(
  305. serial=serial,
  306. name=os.path.basename(folder),
  307. path=self.path,
  308. )
  309. def iter_adb_binaries(self) -> t.Iterable[str]:
  310. """
  311. Yields:
  312. str: Filepath to adb binaries found in this emulator
  313. """
  314. if self == Emulator.NoxPlayerFamily:
  315. exe = self.abspath('./nox_adb.exe')
  316. if os.path.exists(exe):
  317. yield exe
  318. if self == Emulator.MuMuPlayerFamily:
  319. # From MuMu9\emulator\nemu9\EmulatorShell
  320. # to MuMu9\emulator\nemu9\vmonitor\bin\adb_server.exe
  321. exe = self.abspath('../vmonitor/bin/adb_server.exe')
  322. if os.path.exists(exe):
  323. yield exe
  324. # All emulators have adb.exe
  325. exe = self.abspath('./adb.exe')
  326. if os.path.exists(exe):
  327. yield exe
  328. class EmulatorManager(EmulatorManagerBase):
  329. @staticmethod
  330. def iter_user_assist():
  331. """
  332. Get recently executed programs in UserAssist
  333. https://github.com/forensicmatt/MonitorUserAssist
  334. Yields:
  335. str: Path to emulator executables, may contains duplicate values
  336. """
  337. path = r'Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist'
  338. # {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\xxx.exe
  339. regex_hash = re.compile(r'{.*}')
  340. try:
  341. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as reg:
  342. folders = list_key(reg)
  343. except FileNotFoundError:
  344. return
  345. for folder in folders:
  346. try:
  347. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, f'{path}\\{folder}\\Count') as reg:
  348. for key in list_reg(reg):
  349. key = codecs.decode(key.name, 'rot-13')
  350. # Skip those with hash
  351. if regex_hash.search(key):
  352. continue
  353. for file in Emulator.multi_to_single(key):
  354. yield file
  355. except FileNotFoundError:
  356. # FileNotFoundError: [WinError 2] 系统找不到指定的文件。
  357. # Might be a random directory without "Count" subdirectory
  358. continue
  359. @staticmethod
  360. def iter_mui_cache():
  361. """
  362. Iter emulator executables that has ever run.
  363. http://what-when-how.com/windows-forensic-analysis/registry-analysis-windows-forensic-analysis-part-8/
  364. https://3gstudent.github.io/%E6%B8%97%E9%80%8F%E6%8A%80%E5%B7%A7-Windows%E7%B3%BB%E7%BB%9F%E6%96%87%E4%BB%B6%E6%89%A7%E8%A1%8C%E8%AE%B0%E5%BD%95%E7%9A%84%E8%8E%B7%E5%8F%96%E4%B8%8E%E6%B8%85%E9%99%A4
  365. Yields:
  366. str: Path to emulator executable, may contains duplicate values
  367. """
  368. path = r'Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\MuiCache'
  369. try:
  370. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as reg:
  371. rows = list_reg(reg)
  372. except FileNotFoundError:
  373. return
  374. regex = re.compile(r'(^.*\.exe)\.')
  375. for row in rows:
  376. res = regex.search(row.name)
  377. if not res:
  378. continue
  379. for file in Emulator.multi_to_single(res.group(1)):
  380. yield file
  381. @staticmethod
  382. def get_install_dir_from_reg(path, key):
  383. """
  384. Args:
  385. path (str): f'SOFTWARE\\leidian\\ldplayer'
  386. key (str): 'InstallDir'
  387. Returns:
  388. str: Installation dir or None
  389. """
  390. try:
  391. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as reg:
  392. root = winreg.QueryValueEx(reg, key)[0]
  393. return root
  394. except FileNotFoundError:
  395. pass
  396. try:
  397. with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) as reg:
  398. root = winreg.QueryValueEx(reg, key)[0]
  399. return root
  400. except FileNotFoundError:
  401. pass
  402. return None
  403. @staticmethod
  404. def iter_uninstall_registry():
  405. """
  406. Iter emulator uninstaller from registry.
  407. Yields:
  408. str: Path to uninstall exe file
  409. """
  410. known_uninstall_registry_path = [
  411. r'SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall',
  412. r'Software\Microsoft\Windows\CurrentVersion\Uninstall'
  413. ]
  414. known_emulator_registry_name = [
  415. 'Nox',
  416. 'Nox64',
  417. 'BlueStacks',
  418. 'BlueStacks_nxt',
  419. 'BlueStacks_cn',
  420. 'BlueStacks_nxt_cn',
  421. 'LDPlayer',
  422. 'LDPlayer4',
  423. 'LDPlayer9',
  424. 'leidian',
  425. 'leidian4',
  426. 'leidian9',
  427. 'Nemu',
  428. 'Nemu9',
  429. 'MuMuPlayer-12.0'
  430. 'MEmu',
  431. ]
  432. for path in known_uninstall_registry_path:
  433. try:
  434. with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) as reg:
  435. software_list = list_key(reg)
  436. except FileNotFoundError:
  437. continue
  438. for software in software_list:
  439. if software not in known_emulator_registry_name:
  440. continue
  441. try:
  442. with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, f'{path}\\{software}') as software_reg:
  443. uninstall = winreg.QueryValueEx(software_reg, 'UninstallString')[0]
  444. except FileNotFoundError:
  445. continue
  446. if not uninstall:
  447. continue
  448. # UninstallString is like:
  449. # C:\Program Files\BlueStacks_nxt\BlueStacksUninstaller.exe -tmp
  450. # "E:\ProgramFiles\Microvirt\MEmu\uninstall\uninstall.exe" -u
  451. # Extract path in ""
  452. res = re.search('"(.*?)"', uninstall)
  453. uninstall = res.group(1) if res else uninstall
  454. yield uninstall
  455. @staticmethod
  456. def iter_running_emulator():
  457. """
  458. Yields:
  459. str: Path to emulator executables, may contains duplicate values
  460. """
  461. try:
  462. import psutil
  463. except ModuleNotFoundError:
  464. return
  465. # Since this is a one-time-usage, we access psutil._psplatform.Process directly
  466. # to bypass the call of psutil.Process.is_running().
  467. # This only costs about 0.017s.
  468. for pid in psutil.pids():
  469. proc = psutil._psplatform.Process(pid)
  470. try:
  471. exe = proc.cmdline()
  472. exe = exe[0].replace(r'\\', '/').replace('\\', '/')
  473. except (psutil.AccessDenied, psutil.NoSuchProcess, IndexError, OSError):
  474. # psutil.AccessDenied
  475. # NoSuchProcess: process no longer exists (pid=xxx)
  476. # OSError: [WinError 87] 参数错误。: '(originated from ReadProcessMemory)'
  477. continue
  478. if Emulator.is_emulator(exe):
  479. yield exe
  480. @cached_property
  481. def all_emulators(self) -> t.List[Emulator]:
  482. """
  483. Get all emulators installed on current computer.
  484. """
  485. exe = set([])
  486. # MuiCache
  487. for file in EmulatorManager.iter_mui_cache():
  488. if Emulator.is_emulator(file) and os.path.exists(file):
  489. exe.add(file)
  490. # UserAssist
  491. for file in EmulatorManager.iter_user_assist():
  492. if Emulator.is_emulator(file) and os.path.exists(file):
  493. exe.add(file)
  494. # LDPlayer install path
  495. for path in [r'SOFTWARE\leidian\ldplayer',
  496. r'SOFTWARE\leidian\ldplayer9']:
  497. ld = self.get_install_dir_from_reg(path, 'InstallDir')
  498. if ld:
  499. ld = abspath(os.path.join(ld, './dnplayer.exe'))
  500. if Emulator.is_emulator(ld) and os.path.exists(ld):
  501. exe.add(ld)
  502. # Uninstall registry
  503. for uninstall in EmulatorManager.iter_uninstall_registry():
  504. # Find emulator executable from uninstaller
  505. for file in iter_folder(abspath(os.path.dirname(uninstall)), ext='.exe'):
  506. if Emulator.is_emulator(file) and os.path.exists(file):
  507. exe.add(file)
  508. # Find from parent directory
  509. for file in iter_folder(abspath(os.path.join(os.path.dirname(uninstall), '../')), ext='.exe'):
  510. if Emulator.is_emulator(file) and os.path.exists(file):
  511. exe.add(file)
  512. # MuMu specific directory
  513. for file in iter_folder(abspath(os.path.join(os.path.dirname(uninstall), 'EmulatorShell')), ext='.exe'):
  514. if Emulator.is_emulator(file) and os.path.exists(file):
  515. exe.add(file)
  516. # Running
  517. for file in EmulatorManager.iter_running_emulator():
  518. if os.path.exists(file):
  519. exe.add(file)
  520. # De-redundancy
  521. exe = [Emulator(path).path for path in exe if Emulator.is_emulator(path)]
  522. exe = [Emulator(path) for path in remove_duplicated_path(exe)]
  523. return exe
  524. @cached_property
  525. def all_emulator_instances(self) -> t.List[EmulatorInstance]:
  526. """
  527. Get all emulator instances installed on current computer.
  528. """
  529. instances = []
  530. for emulator in self.all_emulators:
  531. instances += list(emulator.iter_instances())
  532. instances: t.List[EmulatorInstance] = sorted(instances, key=lambda x: str(x))
  533. return instances
  534. if __name__ == '__main__':
  535. self = EmulatorManager()
  536. for emu in self.all_emulator_instances:
  537. print(emu)