explore_firmware_uip.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. #!/usr/bin/env python3
  2. """
  3. Live Firmware & UIP Explorer for XJKJ-STL on S1 (Granite Rapids / Hovsee IMC).
  4. Adheres strictly to the methodology in AGENTS.md:
  5. 1. Start SOL capture BEFORE motherboard power-on.
  6. 2. Record baseline -> Read-only query -> Write known parameter -> Verify -> Advance.
  7. 3. Save raw received bytes, command timestamps, and parsed events.
  8. 4. Update firmware commands directory and AUDIT.md with real hardware evidence.
  9. """
  10. import asyncio
  11. import datetime
  12. import json
  13. import os
  14. import re
  15. import sys
  16. import time
  17. from pathlib import Path
  18. BMC_HOST = "192.168.0.100"
  19. BMC_USER = "ADMIN"
  20. BMC_PASS = os.environ.get("STL_BMC_S1_PASSWORD", "Admin123@pl")
  21. BMC_CIPHER = 17
  22. DATA_DIR = Path(__file__).resolve().parent.parent / "data" / "evidence"
  23. DATA_DIR.mkdir(parents=True, exist_ok=True)
  24. SESSION_ID = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  25. RAW_LOG_FILE = DATA_DIR / f"uip_explore_{SESSION_ID}.raw"
  26. EVENT_LOG_FILE = DATA_DIR / f"uip_explore_{SESSION_ID}.jsonl"
  27. def log_event(event_type: str, data: dict):
  28. entry = {
  29. "timestamp_iso": datetime.datetime.now().isoformat(),
  30. "time_monotonic": time.monotonic(),
  31. "event": event_type,
  32. **data
  33. }
  34. with open(EVENT_LOG_FILE, "a", encoding="utf-8") as f:
  35. f.write(json.dumps(entry, ensure_ascii=False) + "\n")
  36. print(f"[{entry['timestamp_iso']}] [{event_type.upper()}] {json.dumps(data, ensure_ascii=False)}")
  37. async def run_ipmi(*args: str) -> str:
  38. env = os.environ.copy()
  39. env["IPMI_PASSWORD"] = BMC_PASS
  40. proc = await asyncio.create_subprocess_exec(
  41. "ipmitool", "-I", "lanplus", "-H", BMC_HOST, "-U", BMC_USER,
  42. "-E", "-C", str(BMC_CIPHER), *args,
  43. stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env
  44. )
  45. stdout, stderr = await proc.communicate()
  46. if proc.returncode != 0:
  47. raise RuntimeError(f"IPMI error: {stderr.decode('utf-8', errors='replace').strip()}")
  48. return stdout.decode("utf-8", errors="replace").strip()
  49. async def get_chassis_power() -> str:
  50. status = await run_ipmi("chassis", "power", "status")
  51. if "is on" in status.lower():
  52. return "on"
  53. if "is off" in status.lower():
  54. return "off"
  55. return "unknown"
  56. class SolCaptureSession:
  57. def __init__(self, raw_path: Path):
  58. self.raw_path = raw_path
  59. self.raw_file = None
  60. self.proc = None
  61. self.buffer = ""
  62. self.lock = asyncio.Lock()
  63. self.connected = asyncio.Event()
  64. async def start(self):
  65. self.raw_file = open(self.raw_path, "wb")
  66. helper_path = Path(__file__).resolve().parent.parent / "native" / "stl_sol_bridge.py"
  67. env = os.environ.copy()
  68. env.update(
  69. STL_SOL_HOST=BMC_HOST,
  70. STL_SOL_USER=BMC_USER,
  71. STL_SOL_PASSWORD=BMC_PASS,
  72. STL_SOL_CIPHER_SUITE=str(BMC_CIPHER),
  73. STL_SOL_STEAL_INUSE="1"
  74. )
  75. self.proc = await asyncio.create_subprocess_exec(
  76. str(helper_path),
  77. stdin=asyncio.subprocess.PIPE,
  78. stdout=asyncio.subprocess.PIPE,
  79. stderr=asyncio.subprocess.PIPE,
  80. env=env
  81. )
  82. asyncio.create_task(self._stderr_reader())
  83. asyncio.create_task(self._stdout_reader())
  84. await asyncio.wait_for(self.connected.wait(), timeout=30.0)
  85. log_event("sol_connected", {"raw_log": str(self.raw_path)})
  86. async def _stderr_reader(self):
  87. while self.proc and self.proc.stderr:
  88. line = await self.proc.stderr.readline()
  89. if not line:
  90. break
  91. try:
  92. msg = json.loads(line.decode())
  93. if msg.get("event") == "ready":
  94. self.connected.set()
  95. log_event("sol_helper_event", msg)
  96. except Exception:
  97. pass
  98. async def _stdout_reader(self):
  99. while self.proc and self.proc.stdout:
  100. chunk = await self.proc.stdout.read(4096)
  101. if not chunk:
  102. break
  103. self.raw_file.write(chunk)
  104. self.raw_file.flush()
  105. text = chunk.decode("utf-8", errors="replace")
  106. sys.stdout.write(text)
  107. sys.stdout.flush()
  108. async with self.lock:
  109. self.buffer += text
  110. if len(self.buffer) > 200000:
  111. self.buffer = self.buffer[-100000:]
  112. async def send_command(self, cmd: str, wait_s: float = 1.0) -> str:
  113. log_event("send_command", {"command": cmd.strip()})
  114. pos_before = len(self.buffer)
  115. payload = (cmd + "\r").encode("utf-8")
  116. self.proc.stdin.write(payload)
  117. await self.proc.stdin.drain()
  118. await asyncio.sleep(wait_s)
  119. async with self.lock:
  120. response = self.buffer[pos_before:]
  121. log_event("command_response", {"command": cmd.strip(), "response": response.strip()})
  122. return response
  123. async def wait_pattern(self, pattern: str, timeout_s: float = 300.0) -> re.Match:
  124. regex = re.compile(pattern)
  125. start_t = time.monotonic()
  126. pos = len(self.buffer)
  127. while time.monotonic() - start_t < timeout_s:
  128. if self.proc and self.proc.returncode is not None:
  129. raise RuntimeError(f"SOL bridge terminated prematurely with code {self.proc.returncode}")
  130. async with self.lock:
  131. match = regex.search(self.buffer[pos:])
  132. if match:
  133. log_event("pattern_matched", {"pattern": pattern, "matched": match.group(0)})
  134. return match
  135. await asyncio.sleep(0.5)
  136. raise TimeoutError(f"Pattern '{pattern}' not observed within {timeout_s}s")
  137. async def close(self):
  138. if self.proc:
  139. try:
  140. self.proc.terminate()
  141. await self.proc.wait()
  142. except Exception:
  143. pass
  144. if self.raw_file:
  145. self.raw_file.close()
  146. log_event("sol_closed", {})
  147. async def main():
  148. print(f"=== Starting Live Firmware & UIP Exploration (Session: {SESSION_ID}) ===")
  149. log_event("session_start", {"session_id": SESSION_ID, "target_bmc": BMC_HOST})
  150. sol = SolCaptureSession(RAW_LOG_FILE)
  151. try:
  152. # Step 1: Ensure Chassis is OFF first
  153. current_power = await get_chassis_power()
  154. log_event("chassis_initial_power", {"power": current_power})
  155. print(f"Initial Chassis Power: {current_power}")
  156. if current_power == "on":
  157. print("Host is ON. Turning OFF for controlled cold boot observation...")
  158. await run_ipmi("chassis", "power", "off")
  159. for _ in range(30):
  160. await asyncio.sleep(1)
  161. p = await get_chassis_power()
  162. if p == "off":
  163. break
  164. print("Chassis confirmed OFF.")
  165. log_event("chassis_powered_off", {})
  166. await asyncio.sleep(3)
  167. # Step 2: Start continuous SOL capture BEFORE motherboard power-on
  168. print("Starting continuous SOL capture while host is OFF...")
  169. await sol.start()
  170. await asyncio.sleep(1)
  171. # Step 3: Power ON host while SOL is actively recording
  172. print("Powering ON host via BMC...")
  173. await run_ipmi("chassis", "power", "on")
  174. log_event("chassis_powered_on", {})
  175. print("Chassis power command sent. Streaming SOL boot sequence...")
  176. # Step 4: Wait for CPU0 UIP Menu
  177. uip_pattern = r"\[0\]\[(Hovsee|CxmtDdrTest)\]Current stage is 1"
  178. print(f"Waiting for CPU0 Stage 1 prompt ('{uip_pattern}')... (timeout: 300s)")
  179. await sol.wait_pattern(uip_pattern, timeout_s=300.0)
  180. # Wait for "Please input your command:"
  181. await sol.wait_pattern(r"\[0\]\[(Hovsee|CxmtDdrTest)\]Please input your command:", timeout_s=15.0)
  182. print("\n>>> CPU0 Stage 1 UIP Prompt Reached! Beginning controlled inspection <<<\n")
  183. # Step 5: Read-only Inspection & Discovery
  184. # 5.1 Send 'list' to observe full built-in command menu
  185. print("[EXPLORE 1/6] Sending 'list' to discover built-in commands...")
  186. list_out = await sol.send_command("list", wait_s=2.0)
  187. # 5.2 Send 'showmain' to observe system baseline configuration
  188. print("[EXPLORE 2/6] Sending 'showmain' to query baseline configuration...")
  189. showmain_out = await sol.send_command("showmain", wait_s=2.0)
  190. # 5.3 Send 'showtrain' to query training mode baseline
  191. print("[EXPLORE 3/6] Sending 'showtrain' to query training status...")
  192. showtrain_out = await sol.send_command("showtrain", wait_s=2.0)
  193. # 5.4 Send 'errhandle disable' (Standard known WA)
  194. print("[EXPLORE 4/6] Sending 'errhandle disable' (known WA setting)...")
  195. errhandle_out = await sol.send_command("errhandle disable", wait_s=1.5)
  196. # 5.5 Send 'ap disable' (Known parameter)
  197. print("[EXPLORE 5/6] Sending 'ap disable'...")
  198. ap_out = await sol.send_command("ap disable", wait_s=1.5)
  199. # 5.6 Exit CPU0 Stage 1 by sending empty newline
  200. print("[EXPLORE 6/6] Sending empty newline to complete CPU0 Stage 1...")
  201. await sol.send_command("", wait_s=2.0)
  202. print("CPU0 Stage 1 completed. Continuing boot...")
  203. # Step 6: Wait for CPU1 UIP Menu
  204. uip_pattern_cpu1 = r"\[1\]\[(Hovsee|CxmtDdrTest)\]Current stage is 1"
  205. print(f"Waiting for CPU1 Stage 1 prompt ('{uip_pattern_cpu1}')... (timeout: 180s)")
  206. try:
  207. await sol.wait_pattern(uip_pattern_cpu1, timeout_s=180.0)
  208. await sol.wait_pattern(r"\[1\]\[(Hovsee|CxmtDdrTest)\]Please input your command:", timeout_s=15.0)
  209. print("\n>>> CPU1 Stage 1 UIP Prompt Reached! <<<\n")
  210. print("Applying verified settings to CPU1...")
  211. await sol.send_command("errhandle disable", wait_s=1.5)
  212. await sol.send_command("ap disable", wait_s=1.5)
  213. await sol.send_command("", wait_s=2.0)
  214. print("CPU1 Stage 1 completed.")
  215. except TimeoutError:
  216. print("CPU1 UIP prompt not seen (single-socket or bypassed). Proceeding.")
  217. # Step 7: Wait for RMT Phase / Temperature telemetry
  218. print("Monitoring for RMT Phase / Sensor output...")
  219. try:
  220. await sol.wait_pattern(r"\[HD_RMTSensor\]N[01]\.C\d+\.D\d+:", timeout_s=360.0)
  221. print(">>> RMT Sensor Output observed! DIMM temperature telemetry active! <<<")
  222. except TimeoutError:
  223. print("RMT Sensor pattern not observed within timeout. Continuing...")
  224. # Step 8: Monitor for AMT prompt or UEFI Shell
  225. print("Monitoring for AMT prompt or UEFI Shell...")
  226. start_wait = time.monotonic()
  227. while time.monotonic() - start_wait < 300.0:
  228. async with sol.lock:
  229. buf = sol.buffer
  230. if "[0][AMT #]" in buf or "[1][AMT #]" in buf:
  231. print(">>> AMT prompt observed! Sending 'exit' to proceed... <<<")
  232. await sol.send_command("exit", wait_s=2.0)
  233. break
  234. if "Shell>" in buf:
  235. print(">>> UEFI Shell prompt reached! <<<")
  236. break
  237. await asyncio.sleep(1.0)
  238. print("\n=== Firmware & UIP Exploration Complete ===")
  239. log_event("session_success", {
  240. "raw_log_path": str(RAW_LOG_FILE),
  241. "event_log_path": str(EVENT_LOG_FILE),
  242. })
  243. except Exception as e:
  244. log_event("session_error", {"error": str(e), "type": type(e).__name__})
  245. print(f"\n[ERROR] Exploration encountered error: {e}", file=sys.stderr)
  246. raise
  247. finally:
  248. await sol.close()
  249. if __name__ == "__main__":
  250. asyncio.run(main())