terminal.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. # Friendly Telegram (telegram userbot)
  2. # Copyright (C) 2018-2019 The Authors
  3. # This program is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU Affero General Public License as published by
  5. # the Free Software Foundation, either version 3 of the License, or
  6. # (at your option) any later version.
  7. # This program is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU Affero General Public License for more details.
  11. # You should have received a copy of the GNU Affero General Public License
  12. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. # ©️ Dan Gazizullin, 2021-2023
  14. # This file is a part of Hikka Userbot
  15. # 🌐 https://github.com/hikariatama/Hikka
  16. # You can redistribute it and/or modify it under the terms of the GNU AGPLv3
  17. # 🔑 https://www.gnu.org/licenses/agpl-3.0.html
  18. # meta developer: @bsolute
  19. import asyncio
  20. import contextlib
  21. import logging
  22. import os
  23. import re
  24. import typing
  25. import hikkatl
  26. from .. import loader, utils
  27. logger = logging.getLogger(__name__)
  28. def hash_msg(message):
  29. return f"{str(utils.get_chat_id(message))}/{str(message.id)}"
  30. async def read_stream(func: callable, stream, delay: float):
  31. last_task = None
  32. data = b""
  33. while True:
  34. dat = await stream.read(1)
  35. if not dat:
  36. # EOF
  37. if last_task:
  38. # Send all pending data
  39. last_task.cancel()
  40. await func(data.decode())
  41. # If there is no last task there is inherently no data, so theres no point sending a blank string
  42. break
  43. data += dat
  44. if last_task:
  45. last_task.cancel()
  46. last_task = asyncio.ensure_future(sleep_for_task(func, data, delay))
  47. async def sleep_for_task(func: callable, data: bytes, delay: float):
  48. await asyncio.sleep(delay)
  49. await func(data.decode())
  50. class MessageEditor:
  51. def __init__(
  52. self,
  53. message: hikkatl.tl.types.Message,
  54. command: str,
  55. config,
  56. strings,
  57. request_message,
  58. ):
  59. self.message = message
  60. self.command = command
  61. self.stdout = ""
  62. self.stderr = ""
  63. self.rc = None
  64. self.redraws = 0
  65. self.config = config
  66. self.strings = strings
  67. self.request_message = request_message
  68. async def update_stdout(self, stdout):
  69. self.stdout = stdout
  70. await self.redraw()
  71. async def update_stderr(self, stderr):
  72. self.stderr = stderr
  73. await self.redraw()
  74. async def redraw(self):
  75. text = self.strings("running").format(utils.escape_html(self.command)) # fmt: skip
  76. if self.rc is not None:
  77. text += self.strings("finished").format(utils.escape_html(str(self.rc)))
  78. text += self.strings("stdout")
  79. text += utils.escape_html(self.stdout[max(len(self.stdout) - 2048, 0) :])
  80. stderr = utils.escape_html(self.stderr[max(len(self.stderr) - 1024, 0) :])
  81. text += (self.strings("stderr") + stderr) if stderr else ""
  82. text += self.strings("end")
  83. with contextlib.suppress(hikkatl.errors.rpcerrorlist.MessageNotModifiedError):
  84. try:
  85. self.message = await utils.answer(self.message, text)
  86. except hikkatl.errors.rpcerrorlist.MessageTooLongError as e:
  87. logger.error(e)
  88. logger.error(text)
  89. # The message is never empty due to the template header
  90. async def cmd_ended(self, rc):
  91. self.rc = rc
  92. self.state = 4
  93. await self.redraw()
  94. def update_process(self, process):
  95. pass
  96. class SudoMessageEditor(MessageEditor):
  97. # Let's just hope these are safe to parse
  98. PASS_REQ = "[sudo] password for"
  99. WRONG_PASS = r"\[sudo\] password for (.*): Sorry, try again\."
  100. TOO_MANY_TRIES = (r"\[sudo\] password for (.*): sudo: [0-9]+ incorrect password attempts") # fmt: skip
  101. def __init__(self, message, command, config, strings, request_message):
  102. super().__init__(message, command, config, strings, request_message)
  103. self.process = None
  104. self.state = 0
  105. self.authmsg = None
  106. def update_process(self, process):
  107. logger.debug("got sproc obj %s", process)
  108. self.process = process
  109. async def update_stderr(self, stderr):
  110. logger.debug("stderr update " + stderr)
  111. self.stderr = stderr
  112. lines = stderr.strip().split("\n")
  113. lastline = lines[-1]
  114. lastlines = lastline.rsplit(" ", 1)
  115. handled = False
  116. if (
  117. len(lines) > 1
  118. and re.fullmatch(self.WRONG_PASS, lines[-2])
  119. and lastlines[0] == self.PASS_REQ
  120. and self.state == 1
  121. ):
  122. logger.debug("switching state to 0")
  123. await self.authmsg.edit(self.strings("auth_failed"))
  124. self.state = 0
  125. handled = True
  126. await asyncio.sleep(2)
  127. await self.authmsg.delete()
  128. if lastlines[0] == self.PASS_REQ and self.state == 0:
  129. logger.debug("Success to find sudo log!")
  130. text = self.strings("auth_needed").format(self._tg_id)
  131. try:
  132. await utils.answer(self.message, text)
  133. except hikkatl.errors.rpcerrorlist.MessageNotModifiedError as e:
  134. logger.debug(e)
  135. logger.debug("edited message with link to self")
  136. command = "<code>" + utils.escape_html(self.command) + "</code>"
  137. user = utils.escape_html(lastlines[1][:-1])
  138. self.authmsg = await self.message[0].client.send_message(
  139. "me",
  140. self.strings("auth_msg").format(command, user),
  141. )
  142. logger.debug("sent message to self")
  143. self.message[0].client.remove_event_handler(self.on_message_edited)
  144. self.message[0].client.add_event_handler(
  145. self.on_message_edited,
  146. hikkatl.events.messageedited.MessageEdited(chats=["me"]),
  147. )
  148. logger.debug("registered handler")
  149. handled = True
  150. if len(lines) > 1 and (
  151. re.fullmatch(self.TOO_MANY_TRIES, lastline) and self.state in {1, 3, 4}
  152. ):
  153. logger.debug("password wrong lots of times")
  154. await utils.answer(self.message, self.strings("auth_locked"))
  155. await self.authmsg.delete()
  156. self.state = 2
  157. handled = True
  158. if not handled:
  159. logger.debug("Didn't find sudo log.")
  160. if self.authmsg is not None:
  161. await self.authmsg[0].delete()
  162. self.authmsg = None
  163. self.state = 2
  164. await self.redraw()
  165. logger.debug(self.state)
  166. async def update_stdout(self, stdout):
  167. self.stdout = stdout
  168. if self.state != 2:
  169. self.state = 3 # Means that we got stdout only
  170. if self.authmsg is not None:
  171. await self.authmsg.delete()
  172. self.authmsg = None
  173. await self.redraw()
  174. async def on_message_edited(self, message):
  175. # Message contains sensitive information.
  176. if self.authmsg is None:
  177. return
  178. logger.debug("got message edit update in self %s", str(message.id))
  179. if hash_msg(message) == hash_msg(self.authmsg):
  180. # The user has provided interactive authentication. Send password to stdin for sudo.
  181. try:
  182. self.authmsg = await utils.answer(message, self.strings("auth_ongoing"))
  183. except hikkatl.errors.rpcerrorlist.MessageNotModifiedError:
  184. # Try to clear personal info if the edit fails
  185. await message.delete()
  186. self.state = 1
  187. self.process.stdin.write(
  188. message.message.message.split("\n", 1)[0].encode() + b"\n"
  189. )
  190. class RawMessageEditor(SudoMessageEditor):
  191. def __init__(
  192. self,
  193. message,
  194. command,
  195. config,
  196. strings,
  197. request_message,
  198. show_done=False,
  199. ):
  200. super().__init__(message, command, config, strings, request_message)
  201. self.show_done = show_done
  202. async def redraw(self):
  203. logger.debug(self.rc)
  204. if self.rc is None:
  205. text = (
  206. "<code>"
  207. + utils.escape_html(self.stdout[max(len(self.stdout) - 4095, 0) :])
  208. + "</code>"
  209. )
  210. elif self.rc == 0:
  211. text = (
  212. "<code>"
  213. + utils.escape_html(self.stdout[max(len(self.stdout) - 4090, 0) :])
  214. + "</code>"
  215. )
  216. else:
  217. text = (
  218. "<code>"
  219. + utils.escape_html(self.stderr[max(len(self.stderr) - 4095, 0) :])
  220. + "</code>"
  221. )
  222. if self.rc is not None and self.show_done:
  223. text += "\n" + self.strings("done")
  224. logger.debug(text)
  225. with contextlib.suppress(
  226. hikkatl.errors.rpcerrorlist.MessageNotModifiedError,
  227. hikkatl.errors.rpcerrorlist.MessageEmptyError,
  228. ValueError,
  229. ):
  230. try:
  231. await utils.answer(self.message, text)
  232. except hikkatl.errors.rpcerrorlist.MessageTooLongError as e:
  233. logger.error(e)
  234. logger.error(text)
  235. @loader.tds
  236. class TerminalMod(loader.Module):
  237. """Runs commands"""
  238. strings = {"name": "Terminal"}
  239. def __init__(self):
  240. self.config = loader.ModuleConfig(
  241. loader.ConfigValue(
  242. "FLOOD_WAIT_PROTECT",
  243. 2,
  244. lambda: self.strings("fw_protect"),
  245. validator=loader.validators.Integer(minimum=0),
  246. ),
  247. )
  248. self.activecmds = {}
  249. @loader.command()
  250. async def terminalcmd(self, message):
  251. await self.run_command(message, utils.get_args_raw(message))
  252. @loader.command()
  253. async def aptcmd(self, message):
  254. await self.run_command(
  255. message,
  256. ("apt " if os.geteuid() == 0 else "sudo -S apt ")
  257. + utils.get_args_raw(message)
  258. + " -y",
  259. RawMessageEditor(
  260. message,
  261. f"apt {utils.get_args_raw(message)}",
  262. self.config,
  263. self.strings,
  264. message,
  265. True,
  266. ),
  267. )
  268. async def run_command(
  269. self,
  270. message: hikkatl.tl.types.Message,
  271. cmd: str,
  272. editor: typing.Optional[MessageEditor] = None,
  273. ):
  274. if len(cmd.split(" ")) > 1 and cmd.split(" ")[0] == "sudo":
  275. needsswitch = True
  276. for word in cmd.split(" ", 1)[1].split(" "):
  277. if word[0] != "-":
  278. break
  279. if word == "-S":
  280. needsswitch = False
  281. if needsswitch:
  282. cmd = " ".join([cmd.split(" ", 1)[0], "-S", cmd.split(" ", 1)[1]])
  283. sproc = await asyncio.create_subprocess_shell(
  284. cmd,
  285. stdin=asyncio.subprocess.PIPE,
  286. stdout=asyncio.subprocess.PIPE,
  287. stderr=asyncio.subprocess.PIPE,
  288. cwd=utils.get_base_dir(),
  289. )
  290. if editor is None:
  291. editor = SudoMessageEditor(message, cmd, self.config, self.strings, message)
  292. editor.update_process(sproc)
  293. self.activecmds[hash_msg(message)] = sproc
  294. await editor.redraw()
  295. await asyncio.gather(
  296. read_stream(
  297. editor.update_stdout,
  298. sproc.stdout,
  299. self.config["FLOOD_WAIT_PROTECT"],
  300. ),
  301. read_stream(
  302. editor.update_stderr,
  303. sproc.stderr,
  304. self.config["FLOOD_WAIT_PROTECT"],
  305. ),
  306. )
  307. await editor.cmd_ended(await sproc.wait())
  308. del self.activecmds[hash_msg(message)]
  309. @loader.command()
  310. async def terminatecmd(self, message):
  311. if not message.is_reply:
  312. await utils.answer(message, self.strings("what_to_kill"))
  313. return
  314. if hash_msg(await message.get_reply_message()) in self.activecmds:
  315. try:
  316. if "-f" not in utils.get_args_raw(message):
  317. self.activecmds[
  318. hash_msg(await message.get_reply_message())
  319. ].terminate()
  320. else:
  321. self.activecmds[hash_msg(await message.get_reply_message())].kill()
  322. except Exception:
  323. logger.exception("Killing process failed")
  324. await utils.answer(message, self.strings("kill_fail"))
  325. else:
  326. await utils.answer(message, self.strings("killed"))
  327. else:
  328. await utils.answer(message, self.strings("no_cmd"))