#!/usr/bin/env python3 """OpenBMC host console over SSH: raw stdin/stdout, JSON status on stderr. This connects to the configured host-console SSH port, not the BMC Linux shell. It never sends a CR, changes BIOS settings, reconnects, or replays input by itself. """ import contextlib import json import os from pathlib import Path import pty import select import signal import subprocess import sys import time import tty def status(event, code=0): print(json.dumps({"event": event, "code": code}), file=sys.stderr, flush=True) class SshStatus: """Interpret only SSH's independent diagnostic stream, never console bytes.""" def __init__(self): self.buffer = b"" self.authenticated = False self.shell_accepted = False self.error = 0 @property def ready(self): return self.authenticated and self.shell_accepted and not self.error def feed(self, data): self.buffer = (self.buffer + data)[-65536:] text = self.buffer.lower() self.authenticated = self.authenticated or b"authenticated to " in text self.shell_accepted = self.shell_accepted or b"shell request accepted on channel " in text if b"remote host identification has changed" in text or b"host key verification failed" in text: self.error = 1011 elif b"permission denied" in text or b"authentication failed" in text: self.error = 1010 elif b"shell request failed" in text or b"pty allocation request failed" in text: self.error = 1012 def main(): if sys.argv[1:] == ["--help"]: print("STL_SOL_HOST, STL_SOL_USER, STL_SOL_PASSWORD; optional STL_SSH_PORT=2200, " "STL_SSH_KNOWN_HOSTS=data/ssh_known_hosts", file=sys.stderr) return 0 host, user, secret = (os.environ.get(k) for k in ("STL_SOL_HOST", "STL_SOL_USER", "STL_SOL_PASSWORD")) try: port = int(os.environ.get("STL_SSH_PORT", "2200")) if not all((host, user, secret)) or host.startswith("-") or not 1 <= port <= 65535: raise ValueError("Invalid SSH console settings") known_hosts = Path(os.environ.get("STL_SSH_KNOWN_HOSTS", "data/ssh_known_hosts")).resolve() known_hosts.parent.mkdir(parents=True, exist_ok=True) except (ValueError, OSError): status("error", 1002) return 2 stopped = False def stop(signum, frame): nonlocal stopped stopped = True signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) env = os.environ.copy() env["SSHPASS"] = secret # The child only needs sshpass's environment name; never place secrets in argv. env.pop("STL_SOL_PASSWORD", None) env["LC_ALL"] = "C" command = ["sshpass", "-e", "ssh", "-tt", "-vv", "-p", str(port), "-l", user, "-o", "StrictHostKeyChecking=accept-new", "-o", "UserKnownHostsFile=" + str(known_hosts), "-o", "NumberOfPasswordPrompts=1", "-o", "PreferredAuthentications=password,keyboard-interactive", "-o", "PubkeyAuthentication=no", "-o", "ConnectTimeout=8", "-o", "ConnectionAttempts=1", "-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=2", "-o", "EscapeChar=none", host] master, slave = pty.openpty() tty.setraw(slave) proc = None try: proc = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=subprocess.PIPE, env=env, close_fds=True, start_new_session=True) os.close(slave) slave = None status("connecting") parsed = SshStatus() ready = False master_open = True stderr_open = True deadline = time.monotonic() + 20 while not stopped: if not ready and time.monotonic() >= deadline: status("error", 1007) return 2 sources = ([master] if master_open else []) + ([proc.stderr.fileno()] if stderr_open else []) if ready: sources.append(sys.stdin.fileno()) readable, _, _ = select.select(sources, [], [], 0.2) if stderr_open and proc.stderr.fileno() in readable: data = os.read(proc.stderr.fileno(), 8192) if not data: stderr_open = False else: parsed.feed(data) if parsed.error: status("error", parsed.error) return 2 if not ready and parsed.ready: ready = True status("ready") if master_open and master in readable: try: data = os.read(master, 8192) except OSError: data = b"" if not data: master_open = False else: # Raw remote console output is evidence even if it precedes # the local SSH acknowledgement by a few scheduling ticks. sys.stdout.buffer.write(data) sys.stdout.buffer.flush() if ready and sys.stdin.fileno() in readable: data = os.read(sys.stdin.fileno(), 65536) if not data: break while data: size = os.write(master, data) data = data[size:] if proc.poll() is not None and not master_open and not stderr_open: status("error", 1008 if ready else parsed.error or 1010) return 2 status("closed") return 0 except OSError: status("error", 1005) return 2 finally: if slave is not None: os.close(slave) if proc: # sshpass and SSH share this private process group. Releasing the # network connection does not send exit/Ctrl-C to the BIOS program. with contextlib.suppress(ProcessLookupError): os.killpg(proc.pid, signal.SIGTERM) try: proc.wait(timeout=1) except subprocess.TimeoutExpired: with contextlib.suppress(ProcessLookupError): os.killpg(proc.pid, signal.SIGKILL) proc.wait() if proc.stderr: proc.stderr.close() with contextlib.suppress(OSError): os.close(master) if __name__ == "__main__": sys.exit(main())