stl_ssh_console_bridge.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. #!/usr/bin/env python3
  2. """OpenBMC host console over SSH: raw stdin/stdout, JSON status on stderr.
  3. This connects to the configured host-console SSH port, not the BMC Linux shell.
  4. It never sends a CR, changes BIOS settings, reconnects, or replays input by itself.
  5. """
  6. import contextlib
  7. import json
  8. import os
  9. from pathlib import Path
  10. import pty
  11. import select
  12. import signal
  13. import subprocess
  14. import sys
  15. import time
  16. import tty
  17. def status(event, code=0):
  18. print(json.dumps({"event": event, "code": code}), file=sys.stderr, flush=True)
  19. class SshStatus:
  20. """Interpret only SSH's independent diagnostic stream, never console bytes."""
  21. def __init__(self):
  22. self.buffer = b""
  23. self.authenticated = False
  24. self.shell_accepted = False
  25. self.error = 0
  26. @property
  27. def ready(self):
  28. return self.authenticated and self.shell_accepted and not self.error
  29. def feed(self, data):
  30. self.buffer = (self.buffer + data)[-65536:]
  31. text = self.buffer.lower()
  32. self.authenticated = self.authenticated or b"authenticated to " in text
  33. self.shell_accepted = self.shell_accepted or b"shell request accepted on channel " in text
  34. if b"remote host identification has changed" in text or b"host key verification failed" in text:
  35. self.error = 1011
  36. elif b"permission denied" in text or b"authentication failed" in text:
  37. self.error = 1010
  38. elif b"shell request failed" in text or b"pty allocation request failed" in text:
  39. self.error = 1012
  40. def main():
  41. if sys.argv[1:] == ["--help"]:
  42. print("STL_SOL_HOST, STL_SOL_USER, STL_SOL_PASSWORD; optional STL_SSH_PORT=2200, "
  43. "STL_SSH_KNOWN_HOSTS=data/ssh_known_hosts", file=sys.stderr)
  44. return 0
  45. host, user, secret = (os.environ.get(k) for k in ("STL_SOL_HOST", "STL_SOL_USER", "STL_SOL_PASSWORD"))
  46. try:
  47. port = int(os.environ.get("STL_SSH_PORT", "2200"))
  48. if not all((host, user, secret)) or host.startswith("-") or not 1 <= port <= 65535:
  49. raise ValueError("Invalid SSH console settings")
  50. known_hosts = Path(os.environ.get("STL_SSH_KNOWN_HOSTS", "data/ssh_known_hosts")).resolve()
  51. known_hosts.parent.mkdir(parents=True, exist_ok=True)
  52. except (ValueError, OSError):
  53. status("error", 1002)
  54. return 2
  55. stopped = False
  56. def stop(signum, frame):
  57. nonlocal stopped
  58. stopped = True
  59. signal.signal(signal.SIGTERM, stop)
  60. signal.signal(signal.SIGINT, stop)
  61. env = os.environ.copy()
  62. env["SSHPASS"] = secret
  63. # The child only needs sshpass's environment name; never place secrets in argv.
  64. env.pop("STL_SOL_PASSWORD", None)
  65. env["LC_ALL"] = "C"
  66. command = ["sshpass", "-e", "ssh", "-tt", "-vv", "-p", str(port), "-l", user,
  67. "-o", "StrictHostKeyChecking=accept-new",
  68. "-o", "UserKnownHostsFile=" + str(known_hosts),
  69. "-o", "NumberOfPasswordPrompts=1",
  70. "-o", "PreferredAuthentications=password,keyboard-interactive",
  71. "-o", "PubkeyAuthentication=no", "-o", "ConnectTimeout=8",
  72. "-o", "ConnectionAttempts=1", "-o", "ServerAliveInterval=10",
  73. "-o", "ServerAliveCountMax=2", "-o", "EscapeChar=none", host]
  74. master, slave = pty.openpty()
  75. tty.setraw(slave)
  76. proc = None
  77. try:
  78. proc = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=subprocess.PIPE,
  79. env=env, close_fds=True, start_new_session=True)
  80. os.close(slave)
  81. slave = None
  82. status("connecting")
  83. parsed = SshStatus()
  84. ready = False
  85. master_open = True
  86. stderr_open = True
  87. deadline = time.monotonic() + 20
  88. while not stopped:
  89. if not ready and time.monotonic() >= deadline:
  90. status("error", 1007)
  91. return 2
  92. sources = ([master] if master_open else []) + ([proc.stderr.fileno()] if stderr_open else [])
  93. if ready:
  94. sources.append(sys.stdin.fileno())
  95. readable, _, _ = select.select(sources, [], [], 0.2)
  96. if stderr_open and proc.stderr.fileno() in readable:
  97. data = os.read(proc.stderr.fileno(), 8192)
  98. if not data:
  99. stderr_open = False
  100. else:
  101. parsed.feed(data)
  102. if parsed.error:
  103. status("error", parsed.error)
  104. return 2
  105. if not ready and parsed.ready:
  106. ready = True
  107. status("ready")
  108. if master_open and master in readable:
  109. try:
  110. data = os.read(master, 8192)
  111. except OSError:
  112. data = b""
  113. if not data:
  114. master_open = False
  115. else:
  116. # Raw remote console output is evidence even if it precedes
  117. # the local SSH acknowledgement by a few scheduling ticks.
  118. sys.stdout.buffer.write(data)
  119. sys.stdout.buffer.flush()
  120. if ready and sys.stdin.fileno() in readable:
  121. data = os.read(sys.stdin.fileno(), 65536)
  122. if not data:
  123. break
  124. while data:
  125. size = os.write(master, data)
  126. data = data[size:]
  127. if proc.poll() is not None and not master_open and not stderr_open:
  128. status("error", 1008 if ready else parsed.error or 1010)
  129. return 2
  130. status("closed")
  131. return 0
  132. except OSError:
  133. status("error", 1005)
  134. return 2
  135. finally:
  136. if slave is not None:
  137. os.close(slave)
  138. if proc:
  139. # sshpass and SSH share this private process group. Releasing the
  140. # network connection does not send exit/Ctrl-C to the BIOS program.
  141. with contextlib.suppress(ProcessLookupError):
  142. os.killpg(proc.pid, signal.SIGTERM)
  143. try:
  144. proc.wait(timeout=1)
  145. except subprocess.TimeoutExpired:
  146. with contextlib.suppress(ProcessLookupError):
  147. os.killpg(proc.pid, signal.SIGKILL)
  148. proc.wait()
  149. if proc.stderr:
  150. proc.stderr.close()
  151. with contextlib.suppress(OSError):
  152. os.close(master)
  153. if __name__ == "__main__":
  154. sys.exit(main())