| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287 |
- #!/usr/bin/env python3
- """
- Live Firmware & UIP Explorer for XJKJ-STL on S1 (Granite Rapids / Hovsee IMC).
- Adheres strictly to the methodology in AGENTS.md:
- 1. Start SOL capture BEFORE motherboard power-on.
- 2. Record baseline -> Read-only query -> Write known parameter -> Verify -> Advance.
- 3. Save raw received bytes, command timestamps, and parsed events.
- 4. Update firmware commands directory and AUDIT.md with real hardware evidence.
- """
- import asyncio
- import datetime
- import json
- import os
- import re
- import sys
- import time
- from pathlib import Path
- BMC_HOST = "192.168.0.100"
- BMC_USER = "ADMIN"
- BMC_PASS = os.environ.get("STL_BMC_S1_PASSWORD", "Admin123@pl")
- BMC_CIPHER = 17
- DATA_DIR = Path(__file__).resolve().parent.parent / "data" / "evidence"
- DATA_DIR.mkdir(parents=True, exist_ok=True)
- SESSION_ID = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
- RAW_LOG_FILE = DATA_DIR / f"uip_explore_{SESSION_ID}.raw"
- EVENT_LOG_FILE = DATA_DIR / f"uip_explore_{SESSION_ID}.jsonl"
- def log_event(event_type: str, data: dict):
- entry = {
- "timestamp_iso": datetime.datetime.now().isoformat(),
- "time_monotonic": time.monotonic(),
- "event": event_type,
- **data
- }
- with open(EVENT_LOG_FILE, "a", encoding="utf-8") as f:
- f.write(json.dumps(entry, ensure_ascii=False) + "\n")
- print(f"[{entry['timestamp_iso']}] [{event_type.upper()}] {json.dumps(data, ensure_ascii=False)}")
- async def run_ipmi(*args: str) -> str:
- env = os.environ.copy()
- env["IPMI_PASSWORD"] = BMC_PASS
- proc = await asyncio.create_subprocess_exec(
- "ipmitool", "-I", "lanplus", "-H", BMC_HOST, "-U", BMC_USER,
- "-E", "-C", str(BMC_CIPHER), *args,
- stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env
- )
- stdout, stderr = await proc.communicate()
- if proc.returncode != 0:
- raise RuntimeError(f"IPMI error: {stderr.decode('utf-8', errors='replace').strip()}")
- return stdout.decode("utf-8", errors="replace").strip()
- async def get_chassis_power() -> str:
- status = await run_ipmi("chassis", "power", "status")
- if "is on" in status.lower():
- return "on"
- if "is off" in status.lower():
- return "off"
- return "unknown"
- class SolCaptureSession:
- def __init__(self, raw_path: Path):
- self.raw_path = raw_path
- self.raw_file = None
- self.proc = None
- self.buffer = ""
- self.lock = asyncio.Lock()
- self.connected = asyncio.Event()
- async def start(self):
- self.raw_file = open(self.raw_path, "wb")
- helper_path = Path(__file__).resolve().parent.parent / "native" / "stl_sol_bridge.py"
- env = os.environ.copy()
- env.update(
- STL_SOL_HOST=BMC_HOST,
- STL_SOL_USER=BMC_USER,
- STL_SOL_PASSWORD=BMC_PASS,
- STL_SOL_CIPHER_SUITE=str(BMC_CIPHER),
- STL_SOL_STEAL_INUSE="1"
- )
- self.proc = await asyncio.create_subprocess_exec(
- str(helper_path),
- stdin=asyncio.subprocess.PIPE,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- env=env
- )
- asyncio.create_task(self._stderr_reader())
- asyncio.create_task(self._stdout_reader())
- await asyncio.wait_for(self.connected.wait(), timeout=30.0)
- log_event("sol_connected", {"raw_log": str(self.raw_path)})
- async def _stderr_reader(self):
- while self.proc and self.proc.stderr:
- line = await self.proc.stderr.readline()
- if not line:
- break
- try:
- msg = json.loads(line.decode())
- if msg.get("event") == "ready":
- self.connected.set()
- log_event("sol_helper_event", msg)
- except Exception:
- pass
- async def _stdout_reader(self):
- while self.proc and self.proc.stdout:
- chunk = await self.proc.stdout.read(4096)
- if not chunk:
- break
- self.raw_file.write(chunk)
- self.raw_file.flush()
- text = chunk.decode("utf-8", errors="replace")
- sys.stdout.write(text)
- sys.stdout.flush()
- async with self.lock:
- self.buffer += text
- if len(self.buffer) > 200000:
- self.buffer = self.buffer[-100000:]
- async def send_command(self, cmd: str, wait_s: float = 1.0) -> str:
- log_event("send_command", {"command": cmd.strip()})
- pos_before = len(self.buffer)
- payload = (cmd + "\r").encode("utf-8")
- self.proc.stdin.write(payload)
- await self.proc.stdin.drain()
- await asyncio.sleep(wait_s)
- async with self.lock:
- response = self.buffer[pos_before:]
- log_event("command_response", {"command": cmd.strip(), "response": response.strip()})
- return response
- async def wait_pattern(self, pattern: str, timeout_s: float = 300.0) -> re.Match:
- regex = re.compile(pattern)
- start_t = time.monotonic()
- pos = len(self.buffer)
- while time.monotonic() - start_t < timeout_s:
- if self.proc and self.proc.returncode is not None:
- raise RuntimeError(f"SOL bridge terminated prematurely with code {self.proc.returncode}")
- async with self.lock:
- match = regex.search(self.buffer[pos:])
- if match:
- log_event("pattern_matched", {"pattern": pattern, "matched": match.group(0)})
- return match
- await asyncio.sleep(0.5)
- raise TimeoutError(f"Pattern '{pattern}' not observed within {timeout_s}s")
- async def close(self):
- if self.proc:
- try:
- self.proc.terminate()
- await self.proc.wait()
- except Exception:
- pass
- if self.raw_file:
- self.raw_file.close()
- log_event("sol_closed", {})
- async def main():
- print(f"=== Starting Live Firmware & UIP Exploration (Session: {SESSION_ID}) ===")
- log_event("session_start", {"session_id": SESSION_ID, "target_bmc": BMC_HOST})
- sol = SolCaptureSession(RAW_LOG_FILE)
- try:
- # Step 1: Ensure Chassis is OFF first
- current_power = await get_chassis_power()
- log_event("chassis_initial_power", {"power": current_power})
- print(f"Initial Chassis Power: {current_power}")
- if current_power == "on":
- print("Host is ON. Turning OFF for controlled cold boot observation...")
- await run_ipmi("chassis", "power", "off")
- for _ in range(30):
- await asyncio.sleep(1)
- p = await get_chassis_power()
- if p == "off":
- break
- print("Chassis confirmed OFF.")
- log_event("chassis_powered_off", {})
- await asyncio.sleep(3)
- # Step 2: Start continuous SOL capture BEFORE motherboard power-on
- print("Starting continuous SOL capture while host is OFF...")
- await sol.start()
- await asyncio.sleep(1)
- # Step 3: Power ON host while SOL is actively recording
- print("Powering ON host via BMC...")
- await run_ipmi("chassis", "power", "on")
- log_event("chassis_powered_on", {})
- print("Chassis power command sent. Streaming SOL boot sequence...")
- # Step 4: Wait for CPU0 UIP Menu
- uip_pattern = r"\[0\]\[(Hovsee|CxmtDdrTest)\]Current stage is 1"
- print(f"Waiting for CPU0 Stage 1 prompt ('{uip_pattern}')... (timeout: 300s)")
- await sol.wait_pattern(uip_pattern, timeout_s=300.0)
- # Wait for "Please input your command:"
- await sol.wait_pattern(r"\[0\]\[(Hovsee|CxmtDdrTest)\]Please input your command:", timeout_s=15.0)
- print("\n>>> CPU0 Stage 1 UIP Prompt Reached! Beginning controlled inspection <<<\n")
- # Step 5: Read-only Inspection & Discovery
- # 5.1 Send 'list' to observe full built-in command menu
- print("[EXPLORE 1/6] Sending 'list' to discover built-in commands...")
- list_out = await sol.send_command("list", wait_s=2.0)
- # 5.2 Send 'showmain' to observe system baseline configuration
- print("[EXPLORE 2/6] Sending 'showmain' to query baseline configuration...")
- showmain_out = await sol.send_command("showmain", wait_s=2.0)
- # 5.3 Send 'showtrain' to query training mode baseline
- print("[EXPLORE 3/6] Sending 'showtrain' to query training status...")
- showtrain_out = await sol.send_command("showtrain", wait_s=2.0)
- # 5.4 Send 'errhandle disable' (Standard known WA)
- print("[EXPLORE 4/6] Sending 'errhandle disable' (known WA setting)...")
- errhandle_out = await sol.send_command("errhandle disable", wait_s=1.5)
- # 5.5 Send 'ap disable' (Known parameter)
- print("[EXPLORE 5/6] Sending 'ap disable'...")
- ap_out = await sol.send_command("ap disable", wait_s=1.5)
- # 5.6 Exit CPU0 Stage 1 by sending empty newline
- print("[EXPLORE 6/6] Sending empty newline to complete CPU0 Stage 1...")
- await sol.send_command("", wait_s=2.0)
- print("CPU0 Stage 1 completed. Continuing boot...")
- # Step 6: Wait for CPU1 UIP Menu
- uip_pattern_cpu1 = r"\[1\]\[(Hovsee|CxmtDdrTest)\]Current stage is 1"
- print(f"Waiting for CPU1 Stage 1 prompt ('{uip_pattern_cpu1}')... (timeout: 180s)")
- try:
- await sol.wait_pattern(uip_pattern_cpu1, timeout_s=180.0)
- await sol.wait_pattern(r"\[1\]\[(Hovsee|CxmtDdrTest)\]Please input your command:", timeout_s=15.0)
- print("\n>>> CPU1 Stage 1 UIP Prompt Reached! <<<\n")
- print("Applying verified settings to CPU1...")
- await sol.send_command("errhandle disable", wait_s=1.5)
- await sol.send_command("ap disable", wait_s=1.5)
- await sol.send_command("", wait_s=2.0)
- print("CPU1 Stage 1 completed.")
- except TimeoutError:
- print("CPU1 UIP prompt not seen (single-socket or bypassed). Proceeding.")
- # Step 7: Wait for RMT Phase / Temperature telemetry
- print("Monitoring for RMT Phase / Sensor output...")
- try:
- await sol.wait_pattern(r"\[HD_RMTSensor\]N[01]\.C\d+\.D\d+:", timeout_s=360.0)
- print(">>> RMT Sensor Output observed! DIMM temperature telemetry active! <<<")
- except TimeoutError:
- print("RMT Sensor pattern not observed within timeout. Continuing...")
- # Step 8: Monitor for AMT prompt or UEFI Shell
- print("Monitoring for AMT prompt or UEFI Shell...")
- start_wait = time.monotonic()
- while time.monotonic() - start_wait < 300.0:
- async with sol.lock:
- buf = sol.buffer
- if "[0][AMT #]" in buf or "[1][AMT #]" in buf:
- print(">>> AMT prompt observed! Sending 'exit' to proceed... <<<")
- await sol.send_command("exit", wait_s=2.0)
- break
- if "Shell>" in buf:
- print(">>> UEFI Shell prompt reached! <<<")
- break
- await asyncio.sleep(1.0)
- print("\n=== Firmware & UIP Exploration Complete ===")
- log_event("session_success", {
- "raw_log_path": str(RAW_LOG_FILE),
- "event_log_path": str(EVENT_LOG_FILE),
- })
- except Exception as e:
- log_event("session_error", {"error": str(e), "type": type(e).__name__})
- print(f"\n[ERROR] Exploration encountered error: {e}", file=sys.stderr)
- raise
- finally:
- await sol.close()
- if __name__ == "__main__":
- asyncio.run(main())
|