terminal_tool_sudo.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. """Sudo password plumbing and shell-command rewrites for the terminal tool: per-scope
  2. password cache, /dev/tty prompt, the quote-aware shell scanner behind the real-sudo rewrite
  3. (``sudo -S -p ''``) and the compound-background brace-group rewrite, and the NOPASSWD probe.
  4. Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there so
  5. ``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before."""
  6. import logging
  7. import os
  8. import platform
  9. import re
  10. import shlex
  11. import subprocess
  12. import sys
  13. import threading
  14. import time
  15. from collections.abc import Callable, Iterator
  16. from contextvars import ContextVar
  17. from utils import env_var_enabled
  18. # Log-record parity with the origin module.
  19. logger = logging.getLogger("tools.terminal_tool")
  20. # Interactive sudo password cache, scoped to the session key when present, else callback
  21. # identity (ACP / CLI), else the current thread — so one session can never reuse another's
  22. # cached password in a long-lived process.
  23. _sudo_password_cache: dict[str, str] = {}
  24. _sudo_password_cache_lock = threading.Lock()
  25. # Only populated while invoking a UI callback; preserve the zero-argument callback API.
  26. _sudo_prompt_command: ContextVar[str] = ContextVar("sudo_prompt_command", default="")
  27. def get_sudo_prompt_command() -> str:
  28. """Original command for the current sudo password prompt, or '' outside its callback."""
  29. return _sudo_prompt_command.get()
  30. def _get_sudo_password_cache_scope() -> str:
  31. """Return the cache scope for interactive sudo passwords."""
  32. from tools.terminal_tool import _current_session_key, _get_sudo_password_callback
  33. session_key = _current_session_key()
  34. if session_key:
  35. return f"session:{session_key}"
  36. callback = _get_sudo_password_callback()
  37. if callback is None:
  38. return f"thread:{threading.get_ident()}"
  39. owner = getattr(callback, "__self__", None)
  40. func = getattr(callback, "__func__", None)
  41. if owner is not None and func is not None:
  42. return f"callback-owner:{id(owner)}:{id(func)}"
  43. return f"callback:{id(callback)}"
  44. def _get_cached_sudo_password() -> str:
  45. """Return the cached sudo password for the current scope."""
  46. scope = _get_sudo_password_cache_scope()
  47. with _sudo_password_cache_lock:
  48. return _sudo_password_cache.get(scope, "")
  49. def _set_cached_sudo_password(password: str) -> None:
  50. """Persist a sudo password for the current scope ("" drops the entry)."""
  51. scope = _get_sudo_password_cache_scope()
  52. with _sudo_password_cache_lock:
  53. if password:
  54. _sudo_password_cache[scope] = password
  55. else:
  56. _sudo_password_cache.pop(scope, None)
  57. def _reset_cached_sudo_passwords() -> None:
  58. """Clear all cached sudo passwords (tests / process teardown)."""
  59. with _sudo_password_cache_lock:
  60. _sudo_password_cache.clear()
  61. def _in_delegated_child_context() -> bool:
  62. """True while running inside a delegate_task child. Subagents run on parent-process worker
  63. threads and inherit process-wide ``HERMES_INTERACTIVE=1``, which does NOT mean they can reach
  64. the user: a raw ``/dev/tty`` sudo prompt from a child races the TUI for the tty and blocks the
  65. child for the full timeout, so children are always headless for sudo prompting. The ContextVar
  66. is set by ``delegated_child_context()`` and propagates via ``copy_context``."""
  67. try:
  68. from agent.delegation_context import is_delegated_child_context
  69. return is_delegated_child_context()
  70. except Exception:
  71. return False
  72. _SUDO_HEADLESS_FAILURES = ("sudo: a password is required", "sudo: no tty present", "sudo: a terminal is required")
  73. def _handle_sudo_failure(output: str, env_type: str) -> str:
  74. """Append a SUDO_PASSWORD tip when sudo failed in a headless context
  75. (gateway session, delegate_task child or `hermes chat -q`); otherwise return *output* as is."""
  76. is_gateway = env_var_enabled("HERMES_GATEWAY_SESSION")
  77. no_user = _no_sudo_user()
  78. if not (is_gateway or no_user) or not any(f in output for f in _SUDO_HEADLESS_FAILURES):
  79. return output
  80. from hermes_constants import display_hermes_home as _dhh
  81. if no_user:
  82. return output + (
  83. "\n\n💡 Tip: This session cannot prompt for a sudo password. "
  84. f"Add SUDO_PASSWORD to {_dhh()}/.env on the agent machine, "
  85. "or run the command without sudo."
  86. )
  87. return output + f"\n\n💡 Tip: To enable sudo over messaging, add SUDO_PASSWORD to {_dhh()}/.env on the agent machine."
  88. # sudo -S rejects a bad cached/interactive password with these messages.
  89. _SUDO_WRONG_PASSWORD_MARKERS = (
  90. "sudo: authentication failed",
  91. "sudo: incorrect password attempt",
  92. "sudo: maximum 3 incorrect authentication attempts",
  93. "sudo: 3 incorrect password attempts",
  94. )
  95. def _sudo_wrong_password_failure(output: str) -> bool:
  96. """Return True when sudo rejected a piped password."""
  97. lowered = (output or "").lower()
  98. return any(marker in lowered for marker in _SUDO_WRONG_PASSWORD_MARKERS)
  99. def _invalidate_cached_sudo_on_auth_failure(command: str | None, output: str) -> bool:
  100. """Drop a session-cached sudo password after sudo rejects it. Env-configured
  101. ``SUDO_PASSWORD`` is left alone — an explicit operator choice, not a cache entry."""
  102. if (
  103. "SUDO_PASSWORD" in os.environ
  104. or not _sudo_wrong_password_failure(output)
  105. or _count_real_sudo_invocations(command or "") == 0
  106. or not _get_cached_sudo_password()
  107. ):
  108. return False
  109. _set_cached_sudo_password("")
  110. return True
  111. def _release_tty(tty_fd, old_attrs) -> None:
  112. """Restore echo and close the /dev/tty fd opened by the password reader (best effort)."""
  113. if tty_fd is None:
  114. return
  115. if old_attrs is not None:
  116. try:
  117. import termios as _termios
  118. _termios.tcsetattr(tty_fd, _termios.TCSAFLUSH, old_attrs)
  119. except Exception as e:
  120. logger.debug("Failed to restore terminal attributes: %s", e)
  121. try:
  122. os.close(tty_fd)
  123. except Exception as e:
  124. logger.debug("Failed to close tty fd: %s", e)
  125. def _read_hidden_password(result: dict) -> None:
  126. """Read one line with echo disabled into ``result``. Uses msvcrt on Windows, /dev/tty on Unix."""
  127. tty_fd = old_attrs = None
  128. try:
  129. chars = []
  130. if platform.system() == "Windows":
  131. import msvcrt
  132. while (c := msvcrt.getwch()) not in {"\r", "\n"}:
  133. if c == "\x03":
  134. raise KeyboardInterrupt
  135. chars.append(c)
  136. result["password"] = "".join(chars)
  137. else:
  138. import termios
  139. tty_fd = os.open("/dev/tty", os.O_RDONLY)
  140. old_attrs = termios.tcgetattr(tty_fd)
  141. new_attrs = termios.tcgetattr(tty_fd)
  142. new_attrs[3] = new_attrs[3] & ~termios.ECHO
  143. termios.tcsetattr(tty_fd, termios.TCSAFLUSH, new_attrs)
  144. while (b := os.read(tty_fd, 1)) and b not in {b"\n", b"\r"}:
  145. chars.append(b)
  146. result["password"] = b"".join(chars).decode("utf-8", errors="replace")
  147. except (KeyboardInterrupt, Exception):
  148. result["password"] = ""
  149. finally:
  150. _release_tty(tty_fd, old_attrs)
  151. result["done"] = True
  152. def _prompt_for_sudo_password(timeout_seconds: int = 45, *, command: str = "") -> str:
  153. """Prompt for a sudo password; "" on skip (empty Enter), timeout, or error. Prefers the
  154. CLI-registered callback (prompt_toolkit-integrated); otherwise reads /dev/tty (msvcrt on
  155. Windows) with echo disabled. Human wait time is excluded from tool deadlines (``human_wait_window``)."""
  156. from tools.human_input_hooks import human_input_request
  157. # The password never reaches the hook; only how the prompt ended.
  158. with human_input_request("sudo", prompt=command) as human:
  159. from tools.terminal_tool import _get_sudo_password_callback
  160. _sudo_cb = _get_sudo_password_callback()
  161. if _sudo_cb is not None:
  162. token = _sudo_prompt_command.set(command)
  163. try:
  164. from tools.approval_human_wait import human_wait_window
  165. with human_wait_window():
  166. password = _sudo_cb() or ""
  167. human.outcome = "provided" if password else "skipped"
  168. return password
  169. except Exception:
  170. human.outcome = "error"
  171. return ""
  172. finally:
  173. _sudo_prompt_command.reset(token)
  174. result = {"password": None, "done": False}
  175. try:
  176. os.environ["HERMES_SPINNER_PAUSE"] = "1"
  177. time.sleep(0.2)
  178. print("\n".join((
  179. "",
  180. "┌" + "─" * 58 + "┐",
  181. "│ 🔐 SUDO PASSWORD REQUIRED" + " " * 30 + "│",
  182. "├" + "─" * 58 + "┤",
  183. "│ Enter password below (input is hidden), or: │",
  184. "│ • Press Enter to skip (command fails gracefully) │",
  185. f"│ • Wait {timeout_seconds}s to auto-skip" + " " * 27 + "│",
  186. "└" + "─" * 58 + "┘",
  187. "",
  188. )))
  189. print(" Password (hidden): ", end="", flush=True)
  190. password_thread = threading.Thread(target=_read_hidden_password, args=(result,), daemon=True)
  191. password_thread.start()
  192. from tools.approval_human_wait import human_wait_window
  193. with human_wait_window():
  194. password_thread.join(timeout=timeout_seconds)
  195. if not result["done"]:
  196. print("\n ⏱ Timeout - continuing without sudo\n (Press Enter to dismiss)\n")
  197. sys.stdout.flush()
  198. human.outcome = "timeout"
  199. return ""
  200. password = result["password"] or ""
  201. human.outcome = "provided" if password else "skipped"
  202. # Newline after the hidden input, then the outcome line.
  203. if password:
  204. print("\n ✓ Password received (cached for this session)\n")
  205. else:
  206. print("\n ⏭ Skipped - continuing without sudo\n")
  207. sys.stdout.flush()
  208. return password
  209. except (EOFError, KeyboardInterrupt):
  210. print("\n ⏭ Cancelled - continuing without sudo\n")
  211. sys.stdout.flush()
  212. human.outcome = "cancelled"
  213. return ""
  214. except Exception as e:
  215. print(f"\n [sudo prompt error: {e}] - continuing without sudo\n")
  216. sys.stdout.flush()
  217. human.outcome = "error"
  218. return ""
  219. finally:
  220. os.environ.pop("HERMES_SPINNER_PAUSE", None)
  221. def _looks_like_env_assignment(token: str) -> bool:
  222. """Return True when *token* is a leading shell environment assignment."""
  223. if "=" not in token or token.startswith("="):
  224. return False
  225. name, _value = token.split("=", 1)
  226. return bool(re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name))
  227. # One shell word: single-/double-quoted runs (unterminated ok; backslash escapes inside double
  228. # quotes), a backslash escape (a trailing lone `\` is a plain char), or any non-`;|&()`/space char.
  229. _SHELL_WORD_RE = re.compile(r"""(?:'[^']*'?|"(?:\\.|[^"])*"?|\\.|[^\s;|&()])*""", re.DOTALL)
  230. def _read_shell_token(command: str, start: int) -> tuple[str, int]:
  231. """Read one shell token, preserving quotes/escapes, starting at *start*."""
  232. end = _SHELL_WORD_RE.match(command, start).end() # type: ignore[union-attr] (`*` always matches)
  233. return command[start:end], end
  234. def _scan_shell(command: str, background: bool = False) -> Iterator[tuple[str, int, int, bool]]:
  235. """Quote-aware shell scanner shared by the sudo and compound-background rewriters.
  236. Yields ``(kind, start, end, at_command_start)`` events that tile *command* exactly:
  237. ``ws`` (one whitespace char), ``comment`` (``#`` up to, not including, the newline),
  238. ``op`` (``&& || ;; ; | & ( )``), ``word`` (one ``_read_shell_token`` token). Comments open at word boundaries.
  239. Background mode (compound-background semantics) additionally emits ``escape`` for a bare ``\\x``, ops ``&>``, ``{ `` and a closing
  240. ``}``, and tracks ``(...)``/``{ ... }`` depth: inside a group nothing is an operator, so
  241. every non-structural char (whitespace included) surfaces as a single ``skip`` event.
  242. """
  243. i, n = 0, len(command)
  244. at_start = True
  245. parens = braces = 0
  246. two_char_ops = ("&&", "||", "&>") if background else ("&&", "||", ";;")
  247. while i < n:
  248. ch = command[i]
  249. grouped = parens or braces
  250. was_start = at_start
  251. if ch.isspace():
  252. kind, end = ("skip" if grouped else "ws"), i + 1
  253. at_start = at_start or ch == "\n"
  254. elif ch == "#":
  255. end = command.find("\n", i)
  256. kind, end = "comment", (n if end == -1 else end)
  257. elif background and ch == "\\" and i + 1 < n:
  258. kind, end = "escape", i + 2
  259. elif background and ch in "'\"":
  260. kind, end = "word", _read_shell_token(command, i)[1]
  261. elif background and (
  262. ch in "()" or (ch == "{" and i + 1 < n and command[i + 1].isspace()) or (ch == "}" and braces)
  263. ):
  264. parens = max(0, parens + (ch == "(") - (ch == ")"))
  265. braces += (ch == "{") - (ch == "}")
  266. kind, end = "op", i + 1
  267. elif background and grouped:
  268. kind, end = "skip", i + 1
  269. elif command.startswith(two_char_ops, i):
  270. kind, end, at_start = "op", i + 2, True
  271. elif ch in ";|&()":
  272. kind, end, at_start = "op", i + 1, ch != ")"
  273. else:
  274. token, end = _read_shell_token(command, i)
  275. kind, at_start = "word", bool(at_start and _looks_like_env_assignment(token))
  276. yield kind, i, end, was_start
  277. i = end
  278. def _rewrite_real_sudo_invocations(command: str) -> tuple[str, int]:
  279. """Rewrite literal sudo executable words, preserving their spelling and arguments.
  280. Follow ordinary env options/assignments, not shell payloads or env split strings:
  281. interpreting those requires a second parser and rewriting inside another quoting layer.
  282. """
  283. out: list[str] = []
  284. sudo_count = 0
  285. in_env = env_operand = env_options = False
  286. value_options = {"-u", "--unset", "-C", "--chdir", "-a", "--argv0"}
  287. flag_options = {"-i", "--ignore-environment", "-0", "--null", "-v", "--debug"}
  288. for kind, start, end, at_start in _scan_shell(command):
  289. text = command[start:end]
  290. out.append(text)
  291. if kind == "op" or (kind == "ws" and text == "\n"):
  292. in_env = env_operand = env_options = False
  293. if kind != "word" or not (at_start or in_env):
  294. continue
  295. try:
  296. words = shlex.split(text)
  297. except ValueError:
  298. in_env = False
  299. continue
  300. # Redirections and expansions are not literal executable paths.
  301. if len(words) != 1 or any(char in text for char in "$`*?[]~<>{}"):
  302. in_env = False
  303. continue
  304. word = words[0]
  305. if in_env:
  306. if env_operand:
  307. env_operand = False
  308. continue
  309. if env_options and word in {"-", "--"}:
  310. env_options = False
  311. continue
  312. if env_options and word in value_options:
  313. env_operand = True
  314. continue
  315. if env_options and (word in flag_options or
  316. any(word.startswith(opt + "=") for opt in value_options if opt.startswith("--")) or
  317. any(word.startswith(opt) and len(word) > 2 for opt in ("-u", "-C", "-a"))):
  318. continue
  319. if env_options and word.startswith("-"):
  320. in_env = False
  321. continue
  322. if _looks_like_env_assignment(word):
  323. env_options = False
  324. continue
  325. elif _looks_like_env_assignment(text):
  326. continue
  327. executable = word.rsplit("/", 1)[-1]
  328. in_env = executable == "env"
  329. env_options = in_env
  330. if executable == "sudo":
  331. out[-1] += " -S -p ''"
  332. sudo_count += 1
  333. return "".join(out), sudo_count
  334. def _count_real_sudo_invocations(command: str) -> int:
  335. """Return how many real sudo command words appear in *command*."""
  336. return _rewrite_real_sudo_invocations(command)[1]
  337. def _rewrite_compound_background(command: str) -> str:
  338. """Wrap `A && B &` (or `A || B &`) to `A && { B & }` at depth 0. Bash binds `&&` tighter
  339. than `&`, so `A && B &` backgrounds a subshell that runs B in the foreground and waits for
  340. it; a long-running B leaves that subshell stuck in ``wait4`` forever, and its open stdout
  341. pipe can keep the terminal tool from returning. The brace group keeps `&&`'s
  342. skip-B-on-failure semantics without a fork: bash backgrounds B as a simple command and
  343. exits immediately, orphaning B normally. Redirects (``&>``, ``2>&1``), quoted strings,
  344. comments and ``(...)``/``{ ... }`` bodies never count as the backgrounding ``&`` (see
  345. ``_scan_shell``); tracking brace depth also makes the rewrite idempotent. `(...)` subshells
  346. have the same bug class but are not the common agent pattern; left for a follow-up.
  347. Simple ``cmd &`` is left alone — it doesn't have the subshell-wait bug."""
  348. chain_end = -1 # just after the last depth-0 `&&`/`||` of this statement; -1 = none active
  349. rewrites: list[tuple[int, int]] = [] # (chain_op_end, amp_pos)
  350. for kind, start, end, _ in _scan_shell(command, background=True):
  351. text = command[start:end]
  352. if kind == "op" and text in ("&&", "||"):
  353. chain_end = end
  354. elif kind == "ws" and text == "\n" or kind == "op" and text in (";", "|", "}"):
  355. # Newline / `;` end a statement, `|` starts a pipeline stage, `}` closes a group.
  356. chain_end = -1
  357. elif kind == "op" and text == "&":
  358. # `&&` and `&>` never reach here; a `>&` / `<&` fd target (look back past
  359. # whitespace) is a redirect, anything else is the real background operator.
  360. j = start - 1
  361. while j >= 0 and command[j].isspace():
  362. j -= 1
  363. if j >= 0 and command[j] in "<>":
  364. continue
  365. if chain_end >= 0:
  366. rewrites.append((chain_end, start))
  367. chain_end = -1
  368. # Apply rewrites back-to-front so earlier indices remain valid.
  369. result = command
  370. for chain_end, amp_pos in reversed(rewrites):
  371. # Skip whitespace right after the `&&`/`||` so the brace group opens flush against
  372. # the inner command. `{` needs a trailing space in bash; the closing `}` needs to be
  373. # preceded by `;` or `&` — we're providing `&` from the backgrounding.
  374. insert_pos = chain_end
  375. while insert_pos < amp_pos and result[insert_pos].isspace():
  376. insert_pos += 1
  377. # The consumed `&` also separated the compound from any statement that followed
  378. # on the same line (`A && B & C`); `{ B & } C` is a syntax error, so restore a `;`
  379. # when the suffix resumes with command text. No separator when the suffix already
  380. # starts with a terminator (`;` `&` `|` newline `)` `}`) — except `&>`, which is a
  381. # redirect prefix for the NEXT command, not a terminator. Strip only spaces/tabs:
  382. # a newline already terminates the group.
  383. suffix = result[amp_pos + 1 :]
  384. tail = suffix.lstrip(" \t")
  385. needs_separator = bool(tail) and (tail[0] not in ";\n&|)}" or tail.startswith("&>"))
  386. separator = " ;" if needs_separator else ""
  387. result = result[:insert_pos] + "{ " + result[insert_pos:amp_pos] + "& }" + separator + suffix
  388. return result
  389. def _no_sudo_user() -> bool:
  390. """A delegated child or a `hermes chat -q` run: nobody can answer a sudo prompt. Single-query only
  391. (not _no_user_can_answer): cron strips HERMES_INTERACTIVE and unattended platforms register no sudo callback."""
  392. from tools.approval_context import _is_single_query_approval_context
  393. return _in_delegated_child_context() or _is_single_query_approval_context()
  394. def _transform_sudo_command(
  395. command: str | None,
  396. sudo_nopasswd_check: Callable[[], bool] | None = None,
  397. ) -> tuple[str | None, str | None]:
  398. """Rewrite command-position ``sudo`` executables to ``sudo -S -p ''`` when a password is available (shared by every
  399. execution environment). Returns ``(command, sudo_stdin)``: ``sudo_stdin`` is one password
  400. line per sudo invocation that the caller must PREPEND to the process stdin (sudo -S consumes
  401. exactly one line and passes the rest through, so it's safe alongside the caller's own
  402. stdin_data). Backends transport that merged stream according to their execution API
  403. (pipe, SDK stdin, or staged file). With no password available the command is
  404. returned unchanged and ``sudo_stdin`` is None, so it fails gracefully with "sudo: a password
  405. is required". Password sources, in order: configured SUDO_PASSWORD, the session cache, then
  406. an interactive prompt (45s timeout, cached on success) when a UI is reachable.
  407. ``sudo_nopasswd_check`` (supplied by ``BaseEnvironment``) runs ``sudo -n true`` inside the
  408. selected backend; a True result skips the prompt and the ``-S`` rewrite entirely."""
  409. from tools.terminal_tool import _get_sudo_password_callback
  410. if command is None:
  411. return None, None
  412. transformed, sudo_count = _rewrite_real_sudo_invocations(command)
  413. if sudo_count == 0:
  414. return command, None
  415. # Scope-aware read: under multiplex the process env may hold another profile's SUDO_PASSWORD;
  416. # unscoped callers (UnscopedSecretError) keep the os.environ read.
  417. try:
  418. from agent.secret_scope import get_secret
  419. _configured_password = get_secret("SUDO_PASSWORD")
  420. except Exception:
  421. _configured_password = os.environ.get("SUDO_PASSWORD")
  422. has_configured_password = _configured_password is not None
  423. sudo_password = _configured_password if has_configured_password else _get_cached_sudo_password()
  424. # delegate_task children and `hermes chat -q` inherit HERMES_INTERACTIVE=1 and (for -q) the CLI
  425. # panel callback, but have no user on the other side — always headless; configured password and
  426. # session cache still apply.
  427. should_prompt_for_sudo = (
  428. env_var_enabled("HERMES_INTERACTIVE") or _get_sudo_password_callback() is not None
  429. ) and not _no_sudo_user()
  430. if not has_configured_password and not sudo_password and should_prompt_for_sudo:
  431. # sudoers NOPASSWD must not be forced through the prompt or the -S pipe. The probe is
  432. # a round trip on the selected backend (an ssh exec for SSH), so it only runs when a
  433. # prompt would otherwise fire: headless callers end up at ``(command, None)`` either
  434. # way. Re-probed every call so an expired sudo timestamp cannot silently block.
  435. if sudo_nopasswd_check is not None and sudo_nopasswd_check():
  436. return command, None
  437. sudo_password = _prompt_for_sudo_password(timeout_seconds=45, command=command)
  438. if sudo_password:
  439. _set_cached_sudo_password(sudo_password)
  440. if has_configured_password or sudo_password:
  441. # sudo -S reads one line per invocation: compound `sudo a && sudo b` needs one line each.
  442. return transformed, (sudo_password + "\n") * sudo_count
  443. return command, None