bmc_ssh_hil_sim.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  1. /*
  2. * bmc_ssh_hil_sim.c — Multi-Station Protocol-Authentic Hardware-in-the-Loop (HIL)
  3. * BMC IPMI v2.0 RMCP+ (UDP :623, Cipher Suite 17 / 3 + 24-ch SDR)
  4. * & SSHv2 BIOS Serial Console (TCP :2200 + :22 Probe) Simulator
  5. *
  6. * Zero-shortcut wire-level compatibility with production `stl_native_server`:
  7. * - Real encrypted RMCP+ 2.0 sessions over UDP :623 (`libfreeipmi`)
  8. * - Real 24-slot Full SDR temperature records (`CPU0_DIMM_A0`..`CPU1_DIMM_L0`)
  9. * - Real SSHv2 PTY/Shell sessions over TCP :2200 (`libssh/server.h`)
  10. * - Real-time link fault injection (`SET_LINK`), AC power loss (`SET_POWER`),
  11. * 24-channel thermal sync (`SET_TEMPS`), and power-event streaming over TCP control port.
  12. */
  13. #define _GNU_SOURCE
  14. #include <arpa/inet.h>
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <netinet/in.h>
  18. #include <netinet/tcp.h>
  19. #include <openssl/evp.h>
  20. #include <openssl/hmac.h>
  21. #include <openssl/rand.h>
  22. #include <poll.h>
  23. #include <pthread.h>
  24. #include <signal.h>
  25. #include <stdint.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <sys/socket.h>
  30. #include <sys/types.h>
  31. #include <time.h>
  32. #include <unistd.h>
  33. #include <freeipmi/freeipmi.h>
  34. #include <libssh/callbacks.h>
  35. #include <libssh/libssh.h>
  36. #include <libssh/server.h>
  37. #define MAX_STATIONS 8
  38. #define MAX_RMCP_SESSIONS 32
  39. #define NUM_DIMMS 24
  40. typedef struct {
  41. int in_use;
  42. uint32_t rc_session_id;
  43. uint32_t ms_session_id;
  44. uint8_t auth_alg;
  45. uint8_t integ_alg;
  46. uint8_t conf_alg;
  47. uint8_t max_priv;
  48. uint8_t lookup_flag;
  49. char username[32];
  50. uint8_t username_len;
  51. uint8_t rc_rand[16];
  52. uint8_t ms_rand[16];
  53. uint8_t ms_guid[16];
  54. uint8_t sik[64];
  55. unsigned int sik_len;
  56. uint8_t k1[64];
  57. unsigned int k1_len;
  58. uint8_t k2[64];
  59. unsigned int k2_len;
  60. uint32_t out_seq;
  61. } RmcpSimSession;
  62. typedef struct {
  63. int idx;
  64. char ip[64];
  65. int ipmi_port;
  66. int ssh_port;
  67. int probe22_port;
  68. int uart_bridge_port;
  69. volatile int bmc_up;
  70. volatile int serial_up;
  71. volatile int power_on;
  72. volatile int off_count;
  73. volatile int on_count;
  74. volatile int reset_count;
  75. volatile int cycle_count;
  76. volatile int warm_reset_count;
  77. volatile int ipmi_rx_packets;
  78. volatile int ssh_connect_count;
  79. volatile int ssh_active;
  80. volatile int kill_active_ssh;
  81. int dimm_present[NUM_DIMMS];
  82. int dimm_temp_c[NUM_DIMMS];
  83. uint8_t sdr_records[NUM_DIMMS][64];
  84. unsigned int sdr_record_lens[NUM_DIMMS];
  85. pthread_mutex_t mu;
  86. RmcpSimSession sessions[MAX_RMCP_SESSIONS];
  87. uint32_t next_ms_sid;
  88. int uart_listen_fd;
  89. int uart_client_fd;
  90. pthread_mutex_t uart_mu;
  91. } SimStation;
  92. static SimStation g_stations[MAX_STATIONS];
  93. static int g_num_stations = 0;
  94. static char g_hostkey_path[256] = "";
  95. static volatile int g_running = 1;
  96. static uint8_t ipmb_checksum(const uint8_t *buf, size_t len) {
  97. uint8_t sum = 0;
  98. for (size_t i = 0; i < len; i++) sum = (uint8_t)(sum + buf[i]);
  99. return (uint8_t)(0x100U - sum);
  100. }
  101. static void build_station_sdr_repository(SimStation *st) {
  102. for (int i = 0; i < NUM_DIMMS; i++) {
  103. int cpu = i / 12;
  104. char ch = (char)('A' + (i % 12));
  105. char name[32];
  106. snprintf(name, sizeof(name), "CPU%d_DIMM_%c0", cpu, ch);
  107. size_t nlen = strlen(name);
  108. if (nlen > 16) nlen = 16;
  109. fiid_obj_t obj = fiid_obj_create(tmpl_sdr_full_sensor_record);
  110. fiid_obj_clear(obj);
  111. fiid_obj_set(obj, "record_id", (uint64_t)(i + 1));
  112. fiid_obj_set(obj, "sdr_version_major", 1);
  113. fiid_obj_set(obj, "sdr_version_minor", 5);
  114. fiid_obj_set(obj, "record_type", IPMI_SDR_FORMAT_FULL_SENSOR_RECORD);
  115. fiid_obj_set(obj, "record_length", (uint64_t)(43 + nlen));
  116. fiid_obj_set(obj, "sensor_owner_id.type", 0);
  117. fiid_obj_set(obj, "sensor_owner_id", 0x10); /* 0x20 >> 1 */
  118. fiid_obj_set(obj, "sensor_owner_lun", 0);
  119. fiid_obj_set(obj, "sensor_owner_lun.reserved", 0);
  120. fiid_obj_set(obj, "channel_number", 0);
  121. fiid_obj_set(obj, "sensor_number", (uint64_t)(0x10 + i));
  122. fiid_obj_set(obj, "entity_id", 32); /* Memory Device */
  123. fiid_obj_set(obj, "entity_instance", (uint64_t)(i + 1));
  124. fiid_obj_set(obj, "entity_instance.type", 0);
  125. fiid_obj_set(obj, "sensor_initialization.sensor_scanning", 1);
  126. fiid_obj_set(obj, "sensor_initialization.event_generation", 0);
  127. fiid_obj_set(obj, "sensor_initialization.init_sensor_type", 1);
  128. fiid_obj_set(obj, "sensor_initialization.init_hysteresis", 0);
  129. fiid_obj_set(obj, "sensor_initialization.init_thresholds", 1);
  130. fiid_obj_set(obj, "sensor_initialization.init_events", 0);
  131. fiid_obj_set(obj, "sensor_initialization.init_scanning", 1);
  132. fiid_obj_set(obj, "sensor_initialization.settable_sensor", 0);
  133. fiid_obj_set(obj, "sensor_capabilities.event_message_control_support", 3);
  134. fiid_obj_set(obj, "sensor_capabilities.threshold_access_support", 1);
  135. fiid_obj_set(obj, "sensor_capabilities.hysteresis_support", 0);
  136. fiid_obj_set(obj, "sensor_capabilities.auto_re_arm_support", 1);
  137. fiid_obj_set(obj, "sensor_capabilities.entity_ignore_support", 0);
  138. fiid_obj_set(obj, "sensor_type", 0x01); /* Temperature */
  139. fiid_obj_set(obj, "event_reading_type_code", 0x01); /* Threshold */
  140. fiid_obj_set(obj, "assertion_event_lower_threshold_reading_mask", 0);
  141. fiid_obj_set(obj, "deassertion_event_upper_threshold_reading_mask", 0);
  142. fiid_obj_set(obj, "discrete_reading_settable_threshold_readable_threshold_mask", 0);
  143. fiid_obj_set(obj, "sensor_unit1.percentage", 0);
  144. fiid_obj_set(obj, "sensor_unit1.modifier_unit", 0);
  145. fiid_obj_set(obj, "sensor_unit1.rate_unit", 0);
  146. fiid_obj_set(obj, "sensor_unit1.analog_data_format", 0); /* unsigned */
  147. fiid_obj_set(obj, "sensor_unit2.base_unit", 1); /* Degrees C */
  148. fiid_obj_set(obj, "sensor_unit3.modifier_unit", 0);
  149. fiid_obj_set(obj, "linearization", 0);
  150. fiid_obj_set(obj, "linearization.reserved", 0);
  151. fiid_obj_set(obj, "m_ls", 1);
  152. fiid_obj_set(obj, "tolerance", 0);
  153. fiid_obj_set(obj, "m_ms", 0);
  154. fiid_obj_set(obj, "b_ls", 0);
  155. fiid_obj_set(obj, "accuracy_ls", 0);
  156. fiid_obj_set(obj, "b_ms", 0);
  157. fiid_obj_set(obj, "sensor_direction", 0);
  158. fiid_obj_set(obj, "accuracy_exp", 0);
  159. fiid_obj_set(obj, "accuracy_ms", 0);
  160. fiid_obj_set(obj, "b_exponent", 0);
  161. fiid_obj_set(obj, "r_exponent", 0);
  162. fiid_obj_set(obj, "analog_characteristics_flag.nominal_reading", 1);
  163. fiid_obj_set(obj, "analog_characteristics_flag.normal_max", 1);
  164. fiid_obj_set(obj, "analog_characteristics_flag.normal_min", 1);
  165. fiid_obj_set(obj, "analog_characteristics_flag.reserved", 0);
  166. fiid_obj_set(obj, "nominal_reading", 45);
  167. fiid_obj_set(obj, "normal_maximum", 85);
  168. fiid_obj_set(obj, "normal_minimum", 10);
  169. fiid_obj_set(obj, "sensor_maximum_reading", 125);
  170. fiid_obj_set(obj, "sensor_minimum_reading", 0);
  171. fiid_obj_set(obj, "upper_non_recoverable_threshold", 105);
  172. fiid_obj_set(obj, "upper_critical_threshold", 95);
  173. fiid_obj_set(obj, "upper_non_critical_threshold", 85);
  174. fiid_obj_set(obj, "lower_non_recoverable_threshold", 0);
  175. fiid_obj_set(obj, "lower_critical_threshold", 0);
  176. fiid_obj_set(obj, "lower_non_critical_threshold", 5);
  177. fiid_obj_set(obj, "positive_going_threshold_hysteresis", 1);
  178. fiid_obj_set(obj, "negative_going_threshold_hysteresis", 1);
  179. fiid_obj_set(obj, "reserved", 0);
  180. fiid_obj_set(obj, "oem", 0);
  181. /* ASCII/Latin1 type (0xC0) | length */
  182. fiid_obj_set(obj, "id_string_type_length_code", (uint64_t)(0xC0 | nlen));
  183. fiid_obj_set_data(obj, "id_string", name, (unsigned int)nlen);
  184. int len = fiid_obj_get_all(obj, st->sdr_records[i], sizeof(st->sdr_records[i]));
  185. st->sdr_record_lens[i] = (len > 0) ? (unsigned int)len : 0;
  186. fiid_obj_destroy(obj);
  187. }
  188. }
  189. static void notify_uart_power_event(SimStation *st, const char *ev_name) {
  190. pthread_mutex_lock(&st->uart_mu);
  191. if (st->uart_client_fd >= 0) {
  192. char msg[128];
  193. int n = snprintf(msg, sizeof(msg), "\x01PWR:%s\n", ev_name);
  194. (void)send(st->uart_client_fd, msg, (size_t)n, MSG_NOSIGNAL);
  195. }
  196. pthread_mutex_unlock(&st->uart_mu);
  197. }
  198. static void compute_hmac(
  199. uint8_t auth_alg,
  200. const uint8_t *key, size_t key_len,
  201. const uint8_t *data, size_t data_len,
  202. uint8_t *out, unsigned int *out_len) {
  203. const EVP_MD *md = (auth_alg == IPMI_AUTHENTICATION_ALGORITHM_RAKP_HMAC_SHA1)
  204. ? EVP_sha1()
  205. : EVP_sha256();
  206. HMAC(md, key, (int)key_len, data, data_len, out, out_len);
  207. }
  208. static const char *lookup_password(const char *username) {
  209. (void)username;
  210. return "Admin123@pl";
  211. }
  212. static void handle_ipmi_v15_auth_cap(
  213. int fd, const struct sockaddr_in *cli, socklen_t clilen,
  214. const uint8_t *pkt, ssize_t n) {
  215. /* Minimal IPMI v1.5 unauthenticated Get Channel Authentication Capabilities response */
  216. if (n < 20) return;
  217. uint8_t rq_seq_lun = pkt[18];
  218. uint8_t rq_seq = rq_seq_lun >> 2;
  219. uint8_t rq_addr = pkt[17];
  220. uint8_t rs_addr = pkt[14];
  221. uint8_t resp[32];
  222. memset(resp, 0, sizeof(resp));
  223. /* RMCP header */
  224. resp[0] = 0x06; resp[1] = 0x00; resp[2] = 0xFF; resp[3] = 0x07;
  225. /* v1.5 session header (unauthenticated, seq=0, sid=0, msg_len=16) */
  226. resp[4] = 0x00;
  227. resp[13] = 16;
  228. /* IPMB response header: rqAddr, (netFn=0x07<<2)|0, csum1, rsAddr, (rqSeq<<2)|0, cmd=0x38 */
  229. resp[14] = rq_addr;
  230. resp[15] = (0x07 << 2);
  231. resp[16] = ipmb_checksum(resp + 14, 2);
  232. resp[17] = rs_addr;
  233. resp[18] = (uint8_t)(rq_seq << 2);
  234. resp[19] = 0x38;
  235. resp[20] = 0x00; /* Completion Code OK */
  236. resp[21] = 0x01; /* Channel 1 */
  237. resp[22] = 0x84; /* v2.0+ extended capabilities (0x80) | password (0x04) */
  238. resp[23] = 0x14; /* non-null user, per-msg auth */
  239. resp[24] = 0x02; /* IPMI v2.0 + v1.5 supported */
  240. resp[25] = 0x00; resp[26] = 0x00; resp[27] = 0x00; resp[28] = 0x00;
  241. resp[29] = ipmb_checksum(resp + 17, 12);
  242. (void)sendto(fd, resp, 30, 0, (const struct sockaddr *)cli, clilen);
  243. }
  244. static size_t handle_ipmb_command(
  245. SimStation *st,
  246. RmcpSimSession *sess,
  247. uint8_t net_fn,
  248. uint8_t cmd,
  249. const uint8_t *req_data,
  250. size_t req_len,
  251. uint8_t *rs_data) {
  252. /* rs_data[0] = completion code, followed by response payload */
  253. if (net_fn == 0x06 && cmd == 0x01) {
  254. /* Get Device ID */
  255. rs_data[0] = 0x00;
  256. rs_data[1] = 0x20; /* Device ID */
  257. rs_data[2] = 0x01; /* Device Revision */
  258. rs_data[3] = 0x02; /* FW Major */
  259. rs_data[4] = 0x19; /* FW Minor */
  260. rs_data[5] = 0x02; /* IPMI v2.0 */
  261. rs_data[6] = 0xBF; /* Sensor, SDR, SEL, FRU, Chassis */
  262. rs_data[7] = 0x57; rs_data[8] = 0x01; rs_data[9] = 0x00;
  263. rs_data[10] = 0x01; rs_data[11] = 0x00;
  264. rs_data[12] = 0x00; rs_data[13] = 0x00; rs_data[14] = 0x00; rs_data[15] = 0x00;
  265. return 16;
  266. }
  267. if (net_fn == 0x06 && cmd == 0x3B) {
  268. /* Set Session Privilege Level */
  269. uint8_t req_priv = (req_len >= 1) ? (req_data[0] & 0x0F) : 0x04;
  270. if (req_priv == 0) req_priv = sess ? sess->max_priv : 0x04;
  271. rs_data[0] = 0x00;
  272. rs_data[1] = req_priv;
  273. return 2;
  274. }
  275. if (net_fn == 0x06 && cmd == 0x3C) {
  276. /* Close Session */
  277. if (sess) sess->in_use = 0;
  278. rs_data[0] = 0x00;
  279. return 1;
  280. }
  281. if (net_fn == 0x06 && cmd == 0x02) {
  282. /* Warm Reset */
  283. st->warm_reset_count++;
  284. rs_data[0] = 0x00;
  285. return 1;
  286. }
  287. if (net_fn == 0x00 && cmd == 0x01) {
  288. /* Get Chassis Status */
  289. rs_data[0] = 0x00;
  290. rs_data[1] = st->power_on ? 0x21 : 0x20;
  291. rs_data[2] = 0x00;
  292. rs_data[3] = 0x40;
  293. rs_data[4] = 0x00;
  294. return 5;
  295. }
  296. if (net_fn == 0x00 && cmd == 0x02) {
  297. /* Chassis Control */
  298. uint8_t op = (req_len >= 1) ? (req_data[0] & 0x0F) : 0xFF;
  299. if (op == 0x00) {
  300. st->power_on = 0;
  301. st->off_count++;
  302. notify_uart_power_event(st, "OFF");
  303. } else if (op == 0x01) {
  304. st->power_on = 1;
  305. st->on_count++;
  306. notify_uart_power_event(st, "ON");
  307. } else if (op == 0x02) {
  308. st->power_on = 1;
  309. st->cycle_count++;
  310. notify_uart_power_event(st, "CYCLE");
  311. } else if (op == 0x03) {
  312. st->power_on = 1;
  313. st->reset_count++;
  314. notify_uart_power_event(st, "RESET");
  315. }
  316. rs_data[0] = 0x00;
  317. return 1;
  318. }
  319. if (net_fn == 0x0A && cmd == 0x20) {
  320. /* Get SDR Repository Info */
  321. rs_data[0] = 0x00;
  322. rs_data[1] = 0x51; /* SDR version 1.5 */
  323. rs_data[2] = NUM_DIMMS & 0xFF;
  324. rs_data[3] = (NUM_DIMMS >> 8) & 0xFF;
  325. rs_data[4] = 0x00; rs_data[5] = 0x10; /* Free space */
  326. /* Fixed timestamps so SDR cache stays valid */
  327. rs_data[6] = 0x01; rs_data[7] = 0x00; rs_data[8] = 0x00; rs_data[9] = 0x67;
  328. rs_data[10] = 0x01; rs_data[11] = 0x00; rs_data[12] = 0x00; rs_data[13] = 0x67;
  329. rs_data[14] = 0x02; /* Reserve SDR supported */
  330. return 15;
  331. }
  332. if (net_fn == 0x0A && cmd == 0x22) {
  333. /* Reserve SDR Repository */
  334. rs_data[0] = 0x00;
  335. rs_data[1] = 0x34;
  336. rs_data[2] = 0x12;
  337. return 3;
  338. }
  339. if (net_fn == 0x0A && cmd == 0x23) {
  340. /* Get SDR: [res_ls, res_ms, rec_ls, rec_ms, offset, bytes_to_read] */
  341. if (req_len < 6) {
  342. rs_data[0] = 0xC7;
  343. return 1;
  344. }
  345. uint16_t rec_id = (uint16_t)(req_data[2] | (req_data[3] << 8));
  346. uint8_t offset = req_data[4];
  347. uint8_t to_read = req_data[5];
  348. int idx = (rec_id == 0x0000) ? 0 : ((int)rec_id - 1);
  349. if (idx < 0 || idx >= NUM_DIMMS) {
  350. rs_data[0] = 0xCB; /* Requested sensor/record not present */
  351. return 1;
  352. }
  353. unsigned int rlen = st->sdr_record_lens[idx];
  354. if (offset >= rlen) {
  355. rs_data[0] = 0xC8;
  356. return 1;
  357. }
  358. unsigned int avail = rlen - offset;
  359. unsigned int copy_n = (to_read == 0xFF || to_read > avail) ? avail : to_read;
  360. uint16_t next_id = (idx + 1 < NUM_DIMMS) ? (uint16_t)(idx + 2) : 0xFFFF;
  361. rs_data[0] = 0x00;
  362. rs_data[1] = (uint8_t)(next_id & 0xFF);
  363. rs_data[2] = (uint8_t)((next_id >> 8) & 0xFF);
  364. memcpy(rs_data + 3, st->sdr_records[idx] + offset, copy_n);
  365. return 3 + copy_n;
  366. }
  367. if (net_fn == 0x04 && cmd == 0x2D) {
  368. /* Get Sensor Reading */
  369. if (req_len < 1) {
  370. rs_data[0] = 0xC7;
  371. return 1;
  372. }
  373. int snum = (int)req_data[0] - 0x10;
  374. if (snum < 0 || snum >= NUM_DIMMS) {
  375. rs_data[0] = 0xCB;
  376. return 1;
  377. }
  378. if (!st->power_on || !st->dimm_present[snum]) {
  379. /* Scanning disabled / reading unavailable when powered off or absent */
  380. rs_data[0] = 0x00;
  381. rs_data[1] = 0x00;
  382. rs_data[2] = 0x20; /* bit 5 = reading/state unavailable */
  383. rs_data[3] = 0x00;
  384. return 4;
  385. }
  386. rs_data[0] = 0x00;
  387. rs_data[1] = (uint8_t)(st->dimm_temp_c[snum] & 0xFF);
  388. rs_data[2] = 0x40; /* bit 6 = sensor scanning enabled, bit 5 = 0 (valid!) */
  389. rs_data[3] = 0xC0;
  390. return 4;
  391. }
  392. if (net_fn == 0x04 && cmd == 0x2F) {
  393. /* Get Sensor Type */
  394. rs_data[0] = 0x00;
  395. rs_data[1] = 0x01;
  396. rs_data[2] = 0x01;
  397. return 3;
  398. }
  399. /* Generic OEM / raw fallback (fan control, SEL info, etc.) */
  400. rs_data[0] = 0x00;
  401. rs_data[1] = 0x00;
  402. return 2;
  403. }
  404. static void handle_rmcpplus_packet(
  405. SimStation *st, int fd,
  406. const struct sockaddr_in *cli, socklen_t clilen,
  407. const uint8_t *pkt, ssize_t n) {
  408. if (n < 16) return;
  409. uint8_t ptype_raw = pkt[5];
  410. uint8_t ptype = ptype_raw & 0x3F;
  411. uint32_t sid = (uint32_t)pkt[6] | ((uint32_t)pkt[7] << 8) |
  412. ((uint32_t)pkt[8] << 16) | ((uint32_t)pkt[9] << 24);
  413. uint16_t plen = (uint16_t)pkt[14] | ((uint16_t)pkt[15] << 8);
  414. if (16 + (ssize_t)plen > n) return;
  415. const uint8_t *pl = pkt + 16;
  416. pthread_mutex_lock(&st->mu);
  417. if (ptype == IPMI_PAYLOAD_TYPE_RMCPPLUS_OPEN_SESSION_REQUEST && plen >= 32) {
  418. uint8_t tag = pl[0];
  419. uint8_t req_priv = pl[1] & 0x0F;
  420. if (req_priv == 0) req_priv = 0x04;
  421. uint32_t rc_sid = (uint32_t)pl[4] | ((uint32_t)pl[5] << 8) |
  422. ((uint32_t)pl[6] << 16) | ((uint32_t)pl[7] << 24);
  423. uint8_t auth_alg = pl[12] & 0x3F;
  424. uint8_t integ_alg = pl[20] & 0x3F;
  425. uint8_t conf_alg = pl[28] & 0x3F;
  426. int slot_i = 0;
  427. for (int i = 0; i < MAX_RMCP_SESSIONS; i++) {
  428. if (!st->sessions[i].in_use) { slot_i = i; break; }
  429. }
  430. RmcpSimSession *s = &st->sessions[slot_i];
  431. memset(s, 0, sizeof(*s));
  432. s->in_use = 1;
  433. s->rc_session_id = rc_sid;
  434. s->ms_session_id = ++st->next_ms_sid;
  435. if (s->ms_session_id == 0) s->ms_session_id = ++st->next_ms_sid;
  436. s->auth_alg = auth_alg;
  437. s->integ_alg = integ_alg;
  438. s->conf_alg = conf_alg;
  439. s->max_priv = req_priv;
  440. s->out_seq = 1;
  441. uint8_t resp[16 + 36];
  442. memset(resp, 0, sizeof(resp));
  443. resp[0] = 0x06; resp[1] = 0x00; resp[2] = 0xFF; resp[3] = 0x07;
  444. resp[4] = 0x06; /* RMCP+ */
  445. resp[5] = IPMI_PAYLOAD_TYPE_RMCPPLUS_OPEN_SESSION_RESPONSE;
  446. resp[14] = 36; resp[15] = 0;
  447. uint8_t *rp = resp + 16;
  448. rp[0] = tag;
  449. rp[1] = 0x00; /* status OK */
  450. rp[2] = req_priv;
  451. rp[3] = 0x00;
  452. memcpy(rp + 4, &rc_sid, 4);
  453. memcpy(rp + 8, &s->ms_session_id, 4);
  454. rp[12] = 0x00; rp[15] = 0x08; rp[16] = auth_alg;
  455. rp[20] = 0x01; rp[23] = 0x08; rp[24] = integ_alg;
  456. rp[28] = 0x02; rp[31] = 0x08; rp[32] = conf_alg;
  457. pthread_mutex_unlock(&st->mu);
  458. (void)sendto(fd, resp, sizeof(resp), 0, (const struct sockaddr *)cli, clilen);
  459. return;
  460. }
  461. if (ptype == IPMI_PAYLOAD_TYPE_RAKP_MESSAGE_1 && plen >= 28) {
  462. uint8_t tag = pl[0];
  463. uint32_t ms_sid = (uint32_t)pl[4] | ((uint32_t)pl[5] << 8) |
  464. ((uint32_t)pl[6] << 16) | ((uint32_t)pl[7] << 24);
  465. RmcpSimSession *s = NULL;
  466. for (int i = 0; i < MAX_RMCP_SESSIONS; i++) {
  467. if (st->sessions[i].in_use && st->sessions[i].ms_session_id == ms_sid) {
  468. s = &st->sessions[i];
  469. break;
  470. }
  471. }
  472. if (!s) {
  473. pthread_mutex_unlock(&st->mu);
  474. return;
  475. }
  476. memcpy(s->rc_rand, pl + 8, 16);
  477. uint8_t role_m = pl[24];
  478. s->max_priv = role_m & 0x0F;
  479. s->lookup_flag = (role_m >> 4) & 0x01;
  480. uint8_t ulen = pl[27];
  481. if (ulen > 16 || 28 + ulen > plen) ulen = 0;
  482. s->username_len = ulen;
  483. memset(s->username, 0, sizeof(s->username));
  484. if (ulen > 0) memcpy(s->username, pl + 28, ulen);
  485. RAND_bytes(s->ms_rand, 16);
  486. for (int g = 0; g < 16; g++) s->ms_guid[g] = (uint8_t)(0xA0 + st->idx * 16 + g);
  487. const char *pw = lookup_password(s->username);
  488. uint8_t k_uid[20];
  489. memset(k_uid, 0, sizeof(k_uid));
  490. size_t pw_len = strlen(pw);
  491. if (pw_len > 20) pw_len = 20;
  492. memcpy(k_uid, pw, pw_len);
  493. /* RAKP2 HMAC input: SIDc(4) | SIDm(4) | Rc(16) | Rm(16) | GUIDm(16) | Role_m(1) | ULen(1) | UName */
  494. uint8_t rakp2_in[128];
  495. size_t off = 0;
  496. memcpy(rakp2_in + off, &s->rc_session_id, 4); off += 4;
  497. memcpy(rakp2_in + off, &s->ms_session_id, 4); off += 4;
  498. memcpy(rakp2_in + off, s->rc_rand, 16); off += 16;
  499. memcpy(rakp2_in + off, s->ms_rand, 16); off += 16;
  500. memcpy(rakp2_in + off, s->ms_guid, 16); off += 16;
  501. rakp2_in[off++] = role_m;
  502. rakp2_in[off++] = ulen;
  503. if (ulen > 0) { memcpy(rakp2_in + off, s->username, ulen); off += ulen; }
  504. uint8_t mac[64];
  505. unsigned int mac_len = 0;
  506. compute_hmac(s->auth_alg, k_uid, 20, rakp2_in, off, mac, &mac_len);
  507. /* Derive SIK, K1, K2 via libfreeipmi so keys match client bit-for-bit! */
  508. void *sik_ptr = s->sik, *k1_ptr = s->k1, *k2_ptr = s->k2;
  509. s->sik_len = sizeof(s->sik);
  510. s->k1_len = sizeof(s->k1);
  511. s->k2_len = sizeof(s->k2);
  512. (void)ipmi_calculate_rmcpplus_session_keys(
  513. s->auth_alg, s->integ_alg, s->conf_alg,
  514. pw, (unsigned int)strlen(pw),
  515. NULL, 0,
  516. s->rc_rand, 16,
  517. s->ms_rand, 16,
  518. s->lookup_flag, s->max_priv,
  519. s->username, s->username_len,
  520. &sik_ptr, &s->sik_len,
  521. &k1_ptr, &s->k1_len,
  522. &k2_ptr, &s->k2_len);
  523. uint16_t r2_plen = (uint16_t)(40 + mac_len);
  524. uint8_t resp[16 + 128];
  525. memset(resp, 0, sizeof(resp));
  526. resp[0] = 0x06; resp[1] = 0x00; resp[2] = 0xFF; resp[3] = 0x07;
  527. resp[4] = 0x06;
  528. resp[5] = IPMI_PAYLOAD_TYPE_RAKP_MESSAGE_2;
  529. resp[14] = (uint8_t)(r2_plen & 0xFF);
  530. resp[15] = (uint8_t)((r2_plen >> 8) & 0xFF);
  531. uint8_t *rp = resp + 16;
  532. rp[0] = tag;
  533. rp[1] = 0x00;
  534. memcpy(rp + 4, &s->rc_session_id, 4);
  535. memcpy(rp + 8, s->ms_rand, 16);
  536. memcpy(rp + 24, s->ms_guid, 16);
  537. memcpy(rp + 40, mac, mac_len);
  538. pthread_mutex_unlock(&st->mu);
  539. (void)sendto(fd, resp, 16 + r2_plen, 0, (const struct sockaddr *)cli, clilen);
  540. return;
  541. }
  542. if (ptype == IPMI_PAYLOAD_TYPE_RAKP_MESSAGE_3 && plen >= 8) {
  543. uint8_t tag = pl[0];
  544. uint8_t status_in = pl[1];
  545. uint32_t ms_sid = (uint32_t)pl[4] | ((uint32_t)pl[5] << 8) |
  546. ((uint32_t)pl[6] << 16) | ((uint32_t)pl[7] << 24);
  547. RmcpSimSession *s = NULL;
  548. for (int i = 0; i < MAX_RMCP_SESSIONS; i++) {
  549. if (st->sessions[i].in_use && st->sessions[i].ms_session_id == ms_sid) {
  550. s = &st->sessions[i];
  551. break;
  552. }
  553. }
  554. if (!s || status_in != 0) {
  555. pthread_mutex_unlock(&st->mu);
  556. return;
  557. }
  558. /* Verify RAKP3 client password HMAC (`Admin123@pl` or `ADMIN` both accepted in HIL!) */
  559. const char *cands[2] = { "Admin123@pl", "ADMIN" };
  560. int pw_ok = 0;
  561. for (int ci = 0; ci < 2; ci++) {
  562. uint8_t exp_mac[64];
  563. int exp_len = ipmi_calculate_rakp_3_key_exchange_authentication_code(
  564. s->auth_alg,
  565. cands[ci], (unsigned int)strlen(cands[ci]),
  566. s->ms_rand, 16,
  567. s->rc_session_id,
  568. s->lookup_flag, s->max_priv,
  569. s->username, s->username_len,
  570. exp_mac, sizeof(exp_mac));
  571. if (exp_len > 0 && (size_t)(8 + exp_len) <= plen &&
  572. memcmp(pl + 8, exp_mac, (size_t)exp_len) == 0) {
  573. /* Re-derive SIK/K1/K2 with the matched password if needed */
  574. if (ci == 1) {
  575. void *sik_ptr = s->sik, *k1_ptr = s->k1, *k2_ptr = s->k2;
  576. s->sik_len = sizeof(s->sik);
  577. s->k1_len = sizeof(s->k1);
  578. s->k2_len = sizeof(s->k2);
  579. (void)ipmi_calculate_rmcpplus_session_keys(
  580. s->auth_alg, s->integ_alg, s->conf_alg,
  581. cands[ci], (unsigned int)strlen(cands[ci]),
  582. NULL, 0, s->rc_rand, 16, s->ms_rand, 16,
  583. s->lookup_flag, s->max_priv, s->username, s->username_len,
  584. &sik_ptr, &s->sik_len, &k1_ptr, &s->k1_len, &k2_ptr, &s->k2_len);
  585. }
  586. pw_ok = 1;
  587. break;
  588. }
  589. }
  590. if (!pw_ok) {
  591. uint8_t err_resp[16 + 8];
  592. memset(err_resp, 0, sizeof(err_resp));
  593. err_resp[0] = 0x06; err_resp[2] = 0xFF; err_resp[3] = 0x07;
  594. err_resp[4] = 0x06; err_resp[5] = IPMI_PAYLOAD_TYPE_RAKP_MESSAGE_4;
  595. err_resp[14] = 8;
  596. err_resp[16] = tag;
  597. err_resp[17] = 0x0F; /* Invalid integrity check value */
  598. memcpy(err_resp + 20, &s->rc_session_id, 4);
  599. pthread_mutex_unlock(&st->mu);
  600. (void)sendto(fd, err_resp, sizeof(err_resp), 0, (const struct sockaddr *)cli, clilen);
  601. return;
  602. }
  603. /* RAKP4 ICV: HMAC_SIK(Rc(16) | SIDm(4) | GUIDm(16)), truncated to 12B (SHA1) or 16B (SHA256)! */
  604. uint8_t rakp4_in[36];
  605. memcpy(rakp4_in, s->rc_rand, 16);
  606. memcpy(rakp4_in + 16, &s->ms_session_id, 4);
  607. memcpy(rakp4_in + 20, s->ms_guid, 16);
  608. uint8_t icv[64];
  609. unsigned int icv_full = 0;
  610. compute_hmac(s->auth_alg, s->sik, s->sik_len, rakp4_in, 36, icv, &icv_full);
  611. unsigned int icv_len = (s->auth_alg == IPMI_AUTHENTICATION_ALGORITHM_RAKP_HMAC_SHA256) ? 16 : 12;
  612. uint16_t r4_plen = (uint16_t)(8 + icv_len);
  613. uint8_t resp[16 + 64];
  614. memset(resp, 0, sizeof(resp));
  615. resp[0] = 0x06; resp[1] = 0x00; resp[2] = 0xFF; resp[3] = 0x07;
  616. resp[4] = 0x06;
  617. resp[5] = IPMI_PAYLOAD_TYPE_RAKP_MESSAGE_4;
  618. resp[14] = (uint8_t)(r4_plen & 0xFF);
  619. resp[15] = (uint8_t)((r4_plen >> 8) & 0xFF);
  620. uint8_t *rp = resp + 16;
  621. rp[0] = tag;
  622. rp[1] = 0x00;
  623. memcpy(rp + 4, &s->rc_session_id, 4);
  624. memcpy(rp + 8, icv, icv_len);
  625. pthread_mutex_unlock(&st->mu);
  626. (void)sendto(fd, resp, 16 + r4_plen, 0, (const struct sockaddr *)cli, clilen);
  627. return;
  628. }
  629. if (ptype == IPMI_PAYLOAD_TYPE_IPMI && sid != 0) {
  630. RmcpSimSession *s = NULL;
  631. for (int i = 0; i < MAX_RMCP_SESSIONS; i++) {
  632. if (st->sessions[i].in_use && st->sessions[i].ms_session_id == sid) {
  633. s = &st->sessions[i];
  634. break;
  635. }
  636. }
  637. if (!s) {
  638. pthread_mutex_unlock(&st->mu);
  639. return;
  640. }
  641. /* Decrypt AES-CBC-128 if encrypted, otherwise read raw IPMB request */
  642. uint8_t plain[1024];
  643. int plain_len = 0;
  644. int is_enc = (ptype_raw & 0x80) != 0;
  645. int is_auth = (ptype_raw & 0x40) != 0;
  646. if (is_enc && plen >= 32) {
  647. const uint8_t *iv = pl;
  648. const uint8_t *ct = pl + 16;
  649. int ct_len = (int)plen - 16;
  650. EVP_CIPHER_CTX *cctx = EVP_CIPHER_CTX_new();
  651. EVP_DecryptInit_ex(cctx, EVP_aes_128_cbc(), NULL, s->k2, iv);
  652. EVP_CIPHER_CTX_set_padding(cctx, 0);
  653. int out1 = 0, out2 = 0;
  654. if (EVP_DecryptUpdate(cctx, plain, &out1, ct, ct_len) == 1 &&
  655. EVP_DecryptFinal_ex(cctx, plain + out1, &out2) == 1) {
  656. plain_len = out1 + out2;
  657. }
  658. EVP_CIPHER_CTX_free(cctx);
  659. if (plain_len > 0) {
  660. uint8_t pad_len = plain[plain_len - 1];
  661. if ((int)pad_len + 1 <= plain_len) {
  662. plain_len -= ((int)pad_len + 1);
  663. }
  664. }
  665. } else if (!is_enc) {
  666. memcpy(plain, pl, plen);
  667. plain_len = (int)plen;
  668. }
  669. if (plain_len < 7) {
  670. pthread_mutex_unlock(&st->mu);
  671. return;
  672. }
  673. /* IPMB request: [0]=rsAddr, [1]=(netFn<<2)|rsLUN, [2]=csum1, [3]=rqAddr, [4]=(rqSeq<<2)|rqLUN, [5]=cmd, [6..plain_len-2]=data, [plain_len-1]=csum2 */
  674. uint8_t rs_addr = plain[0];
  675. uint8_t net_fn = (plain[1] >> 2) & 0x3F;
  676. uint8_t rs_lun = plain[1] & 0x03;
  677. uint8_t rq_addr = plain[3];
  678. uint8_t rq_seq = (plain[4] >> 2) & 0x3F;
  679. uint8_t rq_lun = plain[4] & 0x03;
  680. uint8_t cmd = plain[5];
  681. const uint8_t *req_data = plain + 6;
  682. size_t req_len = (size_t)(plain_len - 7);
  683. uint32_t rc_sid = s->rc_session_id;
  684. uint32_t out_seq = s->out_seq++;
  685. uint8_t k1_copy[64], k2_copy[64];
  686. unsigned int k1_len = s->k1_len;
  687. uint8_t integ_alg = s->integ_alg;
  688. memcpy(k1_copy, s->k1, sizeof(k1_copy));
  689. memcpy(k2_copy, s->k2, sizeof(k2_copy));
  690. uint8_t rs_body[512];
  691. size_t rs_body_len = handle_ipmb_command(st, s, net_fn, cmd, req_data, req_len, rs_body);
  692. pthread_mutex_unlock(&st->mu);
  693. /* Build IPMB response message */
  694. uint8_t ipmb_rs[540];
  695. ipmb_rs[0] = rq_addr;
  696. ipmb_rs[1] = (uint8_t)(((net_fn | 0x01) << 2) | rq_lun);
  697. ipmb_rs[2] = ipmb_checksum(ipmb_rs, 2);
  698. ipmb_rs[3] = rs_addr;
  699. ipmb_rs[4] = (uint8_t)((rq_seq << 2) | rs_lun);
  700. ipmb_rs[5] = cmd;
  701. memcpy(ipmb_rs + 6, rs_body, rs_body_len);
  702. size_t ipmb_no_trlr = 6 + rs_body_len;
  703. ipmb_rs[ipmb_no_trlr] = ipmb_checksum(ipmb_rs + 3, ipmb_no_trlr - 3);
  704. size_t ipmb_total = ipmb_no_trlr + 1;
  705. /* Encrypt payload with AES-128-CBC (16B IV + padded plaintext + confidentiality pad 1..N + pad_len) */
  706. uint8_t out_pkt[1200];
  707. memset(out_pkt, 0, sizeof(out_pkt));
  708. out_pkt[0] = 0x06; out_pkt[1] = 0x00; out_pkt[2] = 0xFF; out_pkt[3] = 0x07;
  709. out_pkt[4] = 0x06;
  710. out_pkt[5] = (uint8_t)(IPMI_PAYLOAD_TYPE_IPMI | (is_enc ? 0x80 : 0) | (is_auth ? 0x40 : 0));
  711. memcpy(out_pkt + 6, &rc_sid, 4);
  712. memcpy(out_pkt + 10, &out_seq, 4);
  713. size_t payload_wire_len = 0;
  714. if (is_enc) {
  715. uint8_t iv[16];
  716. RAND_bytes(iv, 16);
  717. uint8_t to_enc[600];
  718. memcpy(to_enc, ipmb_rs, ipmb_total);
  719. size_t rem = (ipmb_total + 1) % 16;
  720. size_t cpad = (rem == 0) ? 0 : (16 - rem);
  721. for (size_t p = 0; p < cpad; p++) to_enc[ipmb_total + p] = (uint8_t)(p + 1);
  722. to_enc[ipmb_total + cpad] = (uint8_t)cpad;
  723. size_t pt_len = ipmb_total + cpad + 1;
  724. memcpy(out_pkt + 16, iv, 16);
  725. EVP_CIPHER_CTX *ectx = EVP_CIPHER_CTX_new();
  726. EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, k2_copy, iv);
  727. EVP_CIPHER_CTX_set_padding(ectx, 0);
  728. int e1 = 0, e2 = 0;
  729. EVP_EncryptUpdate(ectx, out_pkt + 32, &e1, to_enc, (int)pt_len);
  730. EVP_EncryptFinal_ex(ectx, out_pkt + 32 + e1, &e2);
  731. EVP_CIPHER_CTX_free(ectx);
  732. payload_wire_len = 16 + (size_t)(e1 + e2);
  733. } else {
  734. memcpy(out_pkt + 16, ipmb_rs, ipmb_total);
  735. payload_wire_len = ipmb_total;
  736. }
  737. out_pkt[14] = (uint8_t)(payload_wire_len & 0xFF);
  738. out_pkt[15] = (uint8_t)((payload_wire_len >> 8) & 0xFF);
  739. size_t cur_off = 16 + payload_wire_len;
  740. if (is_auth) {
  741. /* Session trailer: integrity pad (0xFF) so (from byte 4 .. next_header inclusive) % 4 == 0 */
  742. size_t covered_base = (cur_off - 4) + 2; /* + pad_len(1) + next_header(1) */
  743. size_t ipad = (4 - (covered_base % 4)) % 4;
  744. for (size_t p = 0; p < ipad; p++) out_pkt[cur_off++] = 0xFF;
  745. out_pkt[cur_off++] = (uint8_t)ipad;
  746. out_pkt[cur_off++] = 0x07; /* Next Header = IPMI */
  747. const EVP_MD *imd = (integ_alg == IPMI_INTEGRITY_ALGORITHM_HMAC_SHA1_96)
  748. ? EVP_sha1()
  749. : EVP_sha256();
  750. unsigned int mac_out_len = 0;
  751. uint8_t full_mac[64];
  752. HMAC(imd, k1_copy, (int)k1_len, out_pkt + 4, cur_off - 4, full_mac, &mac_out_len);
  753. size_t trunc_len = (integ_alg == IPMI_INTEGRITY_ALGORITHM_HMAC_SHA1_96) ? 12 : 16;
  754. memcpy(out_pkt + cur_off, full_mac, trunc_len);
  755. cur_off += trunc_len;
  756. }
  757. (void)sendto(fd, out_pkt, cur_off, 0, (const struct sockaddr *)cli, clilen);
  758. return;
  759. }
  760. pthread_mutex_unlock(&st->mu);
  761. }
  762. static void *ipmi_udp_worker(void *arg) {
  763. SimStation *st = (SimStation *)arg;
  764. int fd = -1;
  765. uint8_t buf[2048];
  766. while (g_running) {
  767. if (st->bmc_up && fd < 0) {
  768. fd = socket(AF_INET, SOCK_DGRAM, 0);
  769. if (fd >= 0) {
  770. int one = 1;
  771. setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
  772. struct sockaddr_in addr;
  773. memset(&addr, 0, sizeof(addr));
  774. addr.sin_family = AF_INET;
  775. addr.sin_port = htons((uint16_t)st->ipmi_port);
  776. inet_pton(AF_INET, st->ip, &addr.sin_addr);
  777. if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
  778. fprintf(stderr, "Failed to bind IPMI UDP %s:%d: %s\n", st->ip, st->ipmi_port, strerror(errno));
  779. close(fd);
  780. fd = -1;
  781. usleep(100000);
  782. continue;
  783. }
  784. }
  785. } else if (!st->bmc_up && fd >= 0) {
  786. close(fd);
  787. fd = -1;
  788. }
  789. if (fd < 0) {
  790. usleep(40000);
  791. continue;
  792. }
  793. struct pollfd pfd = { .fd = fd, .events = POLLIN, .revents = 0 };
  794. if (poll(&pfd, 1, 50) <= 0) continue;
  795. struct sockaddr_in cli;
  796. socklen_t clilen = sizeof(cli);
  797. ssize_t n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&cli, &clilen);
  798. if (n < 4) continue;
  799. if (!st->bmc_up) {
  800. close(fd);
  801. fd = -1;
  802. continue;
  803. }
  804. st->ipmi_rx_packets++;
  805. /* ASF Presence Ping (message class 0x06) */
  806. if ((buf[3] & 0x1F) == 0x06 && n >= 12 && buf[8] == 0x80) {
  807. uint8_t pong[28];
  808. memset(pong, 0, sizeof(pong));
  809. pong[0] = 0x06; pong[2] = 0xFF; pong[3] = 0x06;
  810. pong[4] = 0x00; pong[5] = 0x00; pong[6] = 0x11; pong[7] = 0xBE;
  811. pong[8] = 0x40; pong[9] = buf[9]; pong[11] = 0x10;
  812. pong[12] = 0x00; pong[13] = 0x00; pong[14] = 0x11; pong[15] = 0xBE;
  813. pong[20] = 0x81; /* IPMI supported */
  814. (void)sendto(fd, pong, sizeof(pong), 0, (struct sockaddr *)&cli, clilen);
  815. continue;
  816. }
  817. if ((buf[3] & 0x1F) != 0x07 || n < 5) continue;
  818. if (buf[4] == 0x00) {
  819. handle_ipmi_v15_auth_cap(fd, &cli, clilen, buf, n);
  820. } else if (buf[4] == 0x06) {
  821. handle_rmcpplus_packet(st, fd, &cli, clilen, buf, n);
  822. }
  823. }
  824. if (fd >= 0) close(fd);
  825. return NULL;
  826. }
  827. /* Optional TCP :22 probe responder (closes socket when `bmc_up == 0`) */
  828. static void *tcp_probe22_worker(void *arg) {
  829. SimStation *st = (SimStation *)arg;
  830. if (st->probe22_port <= 0) return NULL;
  831. int lfd = -1;
  832. while (g_running) {
  833. if (st->bmc_up && lfd < 0) {
  834. lfd = socket(AF_INET, SOCK_STREAM, 0);
  835. if (lfd >= 0) {
  836. int one = 1;
  837. setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
  838. struct sockaddr_in a;
  839. memset(&a, 0, sizeof(a));
  840. a.sin_family = AF_INET;
  841. a.sin_port = htons((uint16_t)st->probe22_port);
  842. inet_pton(AF_INET, st->ip, &a.sin_addr);
  843. if (bind(lfd, (struct sockaddr *)&a, sizeof(a)) == 0 && listen(lfd, 8) == 0) {
  844. fcntl(lfd, F_SETFL, O_NONBLOCK);
  845. } else {
  846. close(lfd);
  847. lfd = -1;
  848. }
  849. }
  850. } else if (!st->bmc_up && lfd >= 0) {
  851. close(lfd);
  852. lfd = -1;
  853. }
  854. if (lfd >= 0) {
  855. struct sockaddr_in cli;
  856. socklen_t clilen = sizeof(cli);
  857. int cfd = accept(lfd, (struct sockaddr *)&cli, &clilen);
  858. if (cfd >= 0) {
  859. close(cfd);
  860. continue;
  861. }
  862. }
  863. usleep(40000);
  864. }
  865. if (lfd >= 0) close(lfd);
  866. return NULL;
  867. }
  868. /* Local UART bridge acceptor (`dut_and_hood_sim.py` connects here per station) */
  869. static void *uart_bridge_worker(void *arg) {
  870. SimStation *st = (SimStation *)arg;
  871. int lfd = socket(AF_INET, SOCK_STREAM, 0);
  872. int one = 1;
  873. setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
  874. struct sockaddr_in a;
  875. memset(&a, 0, sizeof(a));
  876. a.sin_family = AF_INET;
  877. a.sin_port = htons((uint16_t)st->uart_bridge_port);
  878. inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);
  879. if (bind(lfd, (struct sockaddr *)&a, sizeof(a)) < 0 || listen(lfd, 4) < 0) {
  880. fprintf(stderr, "Failed to bind UART bridge 127.0.0.1:%d\n", st->uart_bridge_port);
  881. close(lfd);
  882. return NULL;
  883. }
  884. st->uart_listen_fd = lfd;
  885. uint8_t drain_buf[4096];
  886. while (g_running) {
  887. /* When no SSH :2200 client is attached, drain UART TX so disconnected output is genuinely lost (like real HW!) */
  888. if (!st->ssh_active) {
  889. pthread_mutex_lock(&st->uart_mu);
  890. if (st->uart_client_fd >= 0) {
  891. while (recv(st->uart_client_fd, drain_buf, sizeof(drain_buf), MSG_DONTWAIT) > 0) {}
  892. }
  893. pthread_mutex_unlock(&st->uart_mu);
  894. }
  895. struct pollfd pfd = { .fd = lfd, .events = POLLIN, .revents = 0 };
  896. if (poll(&pfd, 1, 40) <= 0) continue;
  897. int cfd = accept(lfd, NULL, NULL);
  898. if (cfd < 0) continue;
  899. setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
  900. fcntl(cfd, F_SETFL, O_NONBLOCK);
  901. pthread_mutex_lock(&st->uart_mu);
  902. if (st->uart_client_fd >= 0) close(st->uart_client_fd);
  903. st->uart_client_fd = cfd;
  904. pthread_mutex_unlock(&st->uart_mu);
  905. }
  906. close(lfd);
  907. return NULL;
  908. }
  909. typedef struct {
  910. SimStation *st;
  911. ssh_session session;
  912. } SshSessionArgs;
  913. static void *ssh_client_handler(void *arg) {
  914. SshSessionArgs *sa = (SshSessionArgs *)arg;
  915. SimStation *st = sa->st;
  916. ssh_session session = sa->session;
  917. free(sa);
  918. if (ssh_handle_key_exchange(session) != SSH_OK) {
  919. ssh_disconnect(session);
  920. ssh_free(session);
  921. return NULL;
  922. }
  923. int authed = 0;
  924. ssh_channel chan = NULL;
  925. int shell_ready = 0;
  926. int loops = 0;
  927. while (g_running && st->serial_up && !st->kill_active_ssh && !shell_ready && loops++ < 400) {
  928. ssh_message msg = ssh_message_get(session);
  929. if (!msg) break;
  930. int mtype = ssh_message_type(msg);
  931. int msub = ssh_message_subtype(msg);
  932. if (mtype == SSH_REQUEST_AUTH) {
  933. if (msub == SSH_AUTH_METHOD_PASSWORD) {
  934. #pragma GCC diagnostic push
  935. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  936. const char *pw = ssh_message_auth_password(msg);
  937. #pragma GCC diagnostic pop
  938. if (pw && (strcmp(pw, "Admin123@pl") == 0 || strcmp(pw, "ADMIN") == 0)) {
  939. authed = 1;
  940. ssh_message_auth_reply_success(msg, 0);
  941. ssh_message_free(msg);
  942. continue;
  943. }
  944. }
  945. ssh_message_auth_set_methods(msg, SSH_AUTH_METHOD_PASSWORD);
  946. ssh_message_reply_default(msg);
  947. } else if (mtype == SSH_REQUEST_CHANNEL_OPEN && msub == SSH_CHANNEL_SESSION && authed) {
  948. chan = ssh_message_channel_request_open_reply_accept(msg);
  949. } else if (mtype == SSH_REQUEST_CHANNEL && chan != NULL) {
  950. if (msub == SSH_CHANNEL_REQUEST_PTY) {
  951. ssh_message_channel_request_reply_success(msg);
  952. } else if (msub == SSH_CHANNEL_REQUEST_SHELL || msub == SSH_CHANNEL_REQUEST_EXEC) {
  953. ssh_message_channel_request_reply_success(msg);
  954. shell_ready = 1;
  955. } else {
  956. ssh_message_channel_request_reply_success(msg);
  957. }
  958. } else {
  959. ssh_message_reply_default(msg);
  960. }
  961. ssh_message_free(msg);
  962. }
  963. if (!shell_ready || !chan) {
  964. if (chan) ssh_channel_free(chan);
  965. ssh_disconnect(session);
  966. ssh_free(session);
  967. return NULL;
  968. }
  969. st->ssh_connect_count++;
  970. st->ssh_active = 1;
  971. uint8_t sbuf[4096];
  972. uint8_t ubuf[8192];
  973. while (g_running && st->serial_up && !st->kill_active_ssh &&
  974. ssh_channel_is_open(chan) && !ssh_channel_is_eof(chan)) {
  975. int did_io = 0;
  976. /* 1. Drain bytes sent from stl_native_server -> forward to Python DUT state machine */
  977. int nr = ssh_channel_read_nonblocking(chan, sbuf, sizeof(sbuf), 0);
  978. if (nr == SSH_ERROR) break;
  979. if (nr > 0) {
  980. did_io = 1;
  981. pthread_mutex_lock(&st->uart_mu);
  982. if (st->uart_client_fd >= 0) {
  983. (void)send(st->uart_client_fd, sbuf, (size_t)nr, MSG_NOSIGNAL);
  984. }
  985. pthread_mutex_unlock(&st->uart_mu);
  986. }
  987. /* 2. Drain BIOS UART bytes from Python DUT state machine -> forward to stl_native_server */
  988. pthread_mutex_lock(&st->uart_mu);
  989. int ufd = st->uart_client_fd;
  990. ssize_t un = -1;
  991. if (ufd >= 0) {
  992. un = recv(ufd, ubuf, sizeof(ubuf), MSG_DONTWAIT);
  993. if (un == 0 || (un < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {
  994. close(st->uart_client_fd);
  995. st->uart_client_fd = -1;
  996. un = -1;
  997. }
  998. }
  999. pthread_mutex_unlock(&st->uart_mu);
  1000. if (un > 0) {
  1001. did_io = 1;
  1002. if (ssh_channel_write(chan, ubuf, (uint32_t)un) == SSH_ERROR) {
  1003. break;
  1004. }
  1005. }
  1006. if (!did_io) usleep(4000);
  1007. }
  1008. st->ssh_active = 0;
  1009. ssh_channel_send_eof(chan);
  1010. ssh_channel_close(chan);
  1011. ssh_channel_free(chan);
  1012. ssh_disconnect(session);
  1013. ssh_free(session);
  1014. return NULL;
  1015. }
  1016. static void *ssh_console_worker(void *arg) {
  1017. SimStation *st = (SimStation *)arg;
  1018. ssh_bind sbind = NULL;
  1019. int listen_fd = -1;
  1020. while (g_running) {
  1021. if (st->serial_up && !sbind) {
  1022. sbind = ssh_bind_new();
  1023. unsigned int port = (unsigned int)st->ssh_port;
  1024. ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_BINDADDR, st->ip);
  1025. ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_BINDPORT, &port);
  1026. ssh_bind_options_set(sbind, SSH_BIND_OPTIONS_HOSTKEY, g_hostkey_path);
  1027. if (ssh_bind_listen(sbind) < 0) {
  1028. ssh_bind_free(sbind);
  1029. sbind = NULL;
  1030. usleep(100000);
  1031. continue;
  1032. }
  1033. ssh_bind_set_blocking(sbind, 0);
  1034. listen_fd = ssh_bind_get_fd(sbind);
  1035. st->kill_active_ssh = 0;
  1036. } else if (!st->serial_up && sbind) {
  1037. st->kill_active_ssh = 1;
  1038. ssh_bind_free(sbind);
  1039. sbind = NULL;
  1040. listen_fd = -1;
  1041. }
  1042. if (sbind && listen_fd >= 0) {
  1043. struct pollfd pfd = { .fd = listen_fd, .events = POLLIN, .revents = 0 };
  1044. if (poll(&pfd, 1, 40) > 0 && (pfd.revents & POLLIN)) {
  1045. ssh_session sess = ssh_new();
  1046. if (ssh_bind_accept(sbind, sess) == SSH_OK) {
  1047. SshSessionArgs *sa = (SshSessionArgs *)calloc(1, sizeof(SshSessionArgs));
  1048. sa->st = st;
  1049. sa->session = sess;
  1050. pthread_t tid;
  1051. if (pthread_create(&tid, NULL, ssh_client_handler, sa) == 0) {
  1052. pthread_detach(tid);
  1053. } else {
  1054. free(sa);
  1055. ssh_free(sess);
  1056. }
  1057. } else {
  1058. ssh_free(sess);
  1059. }
  1060. }
  1061. } else {
  1062. usleep(40000);
  1063. }
  1064. }
  1065. if (sbind) ssh_bind_free(sbind);
  1066. return NULL;
  1067. }
  1068. static void handle_ctrl_line(int cfd, char *line) {
  1069. char cmd[32] = "";
  1070. if (sscanf(line, "%31s", cmd) != 1) return;
  1071. if (strcmp(cmd, "STATUS") == 0) {
  1072. char out[8192];
  1073. size_t off = 0;
  1074. off += (size_t)snprintf(out + off, sizeof(out) - off, "{\"stations\":[");
  1075. for (int i = 0; i < g_num_stations; i++) {
  1076. SimStation *st = &g_stations[i];
  1077. off += (size_t)snprintf(
  1078. out + off, sizeof(out) - off,
  1079. "%s{\"idx\":%d,\"ip\":\"%s\",\"bmc_up\":%s,\"serial_up\":%s,\"power_on\":%s,"
  1080. "\"off_count\":%d,\"on_count\":%d,\"reset_count\":%d,\"cycle_count\":%d,"
  1081. "\"warm_reset_count\":%d,\"ipmi_rx_packets\":%d,\"ssh_connect_count\":%d,\"ssh_active\":%s}",
  1082. (i > 0) ? "," : "",
  1083. st->idx, st->ip,
  1084. st->bmc_up ? "true" : "false",
  1085. st->serial_up ? "true" : "false",
  1086. st->power_on ? "true" : "false",
  1087. st->off_count, st->on_count, st->reset_count, st->cycle_count,
  1088. st->warm_reset_count, st->ipmi_rx_packets, st->ssh_connect_count,
  1089. st->ssh_active ? "true" : "false");
  1090. }
  1091. off += (size_t)snprintf(out + off, sizeof(out) - off, "]}\n");
  1092. (void)send(cfd, out, off, MSG_NOSIGNAL);
  1093. return;
  1094. }
  1095. if (strcmp(cmd, "SET_LINK") == 0) {
  1096. int idx = -1, b_up = 1, s_up = 1;
  1097. if (sscanf(line, "%*s %d %d %d", &idx, &b_up, &s_up) == 3 &&
  1098. idx >= 0 && idx < g_num_stations) {
  1099. SimStation *st = &g_stations[idx];
  1100. st->bmc_up = b_up ? 1 : 0;
  1101. if (!s_up && st->serial_up) {
  1102. st->kill_active_ssh = 1;
  1103. }
  1104. st->serial_up = s_up ? 1 : 0;
  1105. const char *ok = "{\"ok\":true}\n";
  1106. (void)send(cfd, ok, strlen(ok), MSG_NOSIGNAL);
  1107. return;
  1108. }
  1109. }
  1110. if (strcmp(cmd, "SET_POWER") == 0) {
  1111. int idx = -1, pwr = 1;
  1112. if (sscanf(line, "%*s %d %d", &idx, &pwr) == 2 &&
  1113. idx >= 0 && idx < g_num_stations) {
  1114. g_stations[idx].power_on = pwr ? 1 : 0;
  1115. const char *ok = "{\"ok\":true}\n";
  1116. (void)send(cfd, ok, strlen(ok), MSG_NOSIGNAL);
  1117. return;
  1118. }
  1119. }
  1120. if (strcmp(cmd, "SET_TEMPS") == 0) {
  1121. int idx = -1;
  1122. char rest[512] = "";
  1123. if (sscanf(line, "%*s %d %511s", &idx, rest) == 2 &&
  1124. idx >= 0 && idx < g_num_stations) {
  1125. SimStation *st = &g_stations[idx];
  1126. pthread_mutex_lock(&st->mu);
  1127. char *save = NULL;
  1128. char *tok = strtok_r(rest, ",", &save);
  1129. int slot = 0;
  1130. while (tok && slot < NUM_DIMMS) {
  1131. int v = atoi(tok);
  1132. if (v < 0) {
  1133. st->dimm_present[slot] = 0;
  1134. st->dimm_temp_c[slot] = 0;
  1135. } else {
  1136. st->dimm_present[slot] = 1;
  1137. st->dimm_temp_c[slot] = v;
  1138. }
  1139. slot++;
  1140. tok = strtok_r(NULL, ",", &save);
  1141. }
  1142. pthread_mutex_unlock(&st->mu);
  1143. const char *ok = "{\"ok\":true}\n";
  1144. (void)send(cfd, ok, strlen(ok), MSG_NOSIGNAL);
  1145. return;
  1146. }
  1147. }
  1148. if (strcmp(cmd, "QUIT") == 0) {
  1149. g_running = 0;
  1150. const char *ok = "{\"ok\":true}\n";
  1151. (void)send(cfd, ok, strlen(ok), MSG_NOSIGNAL);
  1152. return;
  1153. }
  1154. const char *err = "{\"ok\":false,\"error\":\"bad_command\"}\n";
  1155. (void)send(cfd, err, strlen(err), MSG_NOSIGNAL);
  1156. }
  1157. /*
  1158. * Usage:
  1159. * bmc_ssh_hil_sim --ctrl-port 19199 --uart-base 19200 \
  1160. * --ipmi-port 623 --ssh-port 2200 --probe22-port 22 \
  1161. * 127.0.2.166 127.0.2.165 127.0.2.167 127.0.2.168
  1162. */
  1163. int main(int argc, char **argv) {
  1164. signal(SIGPIPE, SIG_IGN);
  1165. ipmi_rmcpplus_init();
  1166. ssh_init();
  1167. int ctrl_port = 19199;
  1168. int uart_base = 19200;
  1169. int ipmi_port = 623;
  1170. int ssh_port = 2200;
  1171. int probe22_port = 22;
  1172. int argi = 1;
  1173. while (argi < argc && strncmp(argv[argi], "--", 2) == 0) {
  1174. if (strcmp(argv[argi], "--ctrl-port") == 0 && argi + 1 < argc) {
  1175. ctrl_port = atoi(argv[++argi]);
  1176. } else if (strcmp(argv[argi], "--uart-base") == 0 && argi + 1 < argc) {
  1177. uart_base = atoi(argv[++argi]);
  1178. } else if (strcmp(argv[argi], "--ipmi-port") == 0 && argi + 1 < argc) {
  1179. ipmi_port = atoi(argv[++argi]);
  1180. } else if (strcmp(argv[argi], "--ssh-port") == 0 && argi + 1 < argc) {
  1181. ssh_port = atoi(argv[++argi]);
  1182. } else if (strcmp(argv[argi], "--probe22-port") == 0 && argi + 1 < argc) {
  1183. probe22_port = atoi(argv[++argi]);
  1184. } else if (strcmp(argv[argi], "--hostkey") == 0 && argi + 1 < argc) {
  1185. snprintf(g_hostkey_path, sizeof(g_hostkey_path), "%s", argv[++argi]);
  1186. }
  1187. argi++;
  1188. }
  1189. if (g_hostkey_path[0] == '\0') {
  1190. snprintf(g_hostkey_path, sizeof(g_hostkey_path), "/tmp/stl_hil_ssh_hostkey_%d", (int)getpid());
  1191. ssh_key hkey = NULL;
  1192. if (ssh_pki_generate(SSH_KEYTYPE_RSA, 2048, &hkey) != SSH_OK ||
  1193. ssh_pki_export_privkey_file(hkey, NULL, NULL, NULL, g_hostkey_path) != SSH_OK) {
  1194. fprintf(stderr, "Failed to generate ephemeral RSA hostkey at %s\n", g_hostkey_path);
  1195. return 1;
  1196. }
  1197. ssh_key_free(hkey);
  1198. }
  1199. for (; argi < argc && g_num_stations < MAX_STATIONS; argi++) {
  1200. SimStation *st = &g_stations[g_num_stations];
  1201. memset(st, 0, sizeof(*st));
  1202. st->idx = g_num_stations;
  1203. snprintf(st->ip, sizeof(st->ip), "%s", argv[argi]);
  1204. st->ipmi_port = ipmi_port;
  1205. st->ssh_port = ssh_port;
  1206. st->probe22_port = probe22_port;
  1207. st->uart_bridge_port = uart_base + g_num_stations;
  1208. st->bmc_up = 1;
  1209. st->serial_up = 1;
  1210. st->power_on = 1;
  1211. st->next_ms_sid = (uint32_t)(0x10000000U + (uint32_t)g_num_stations * 0x10000U);
  1212. st->uart_listen_fd = -1;
  1213. st->uart_client_fd = -1;
  1214. pthread_mutex_init(&st->mu, NULL);
  1215. pthread_mutex_init(&st->uart_mu, NULL);
  1216. for (int d = 0; d < NUM_DIMMS; d++) {
  1217. st->dimm_present[d] = 1;
  1218. st->dimm_temp_c[d] = 42 + (d % 6);
  1219. }
  1220. build_station_sdr_repository(st);
  1221. g_num_stations++;
  1222. }
  1223. if (g_num_stations == 0) {
  1224. fprintf(stderr, "No station IPs specified\n");
  1225. return 1;
  1226. }
  1227. int ctrl_lfd = socket(AF_INET, SOCK_STREAM, 0);
  1228. int one = 1;
  1229. setsockopt(ctrl_lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
  1230. struct sockaddr_in caddr;
  1231. memset(&caddr, 0, sizeof(caddr));
  1232. caddr.sin_family = AF_INET;
  1233. caddr.sin_port = htons((uint16_t)ctrl_port);
  1234. inet_pton(AF_INET, "127.0.0.1", &caddr.sin_addr);
  1235. if (bind(ctrl_lfd, (struct sockaddr *)&caddr, sizeof(caddr)) < 0 || listen(ctrl_lfd, 16) < 0) {
  1236. fprintf(stderr, "Failed to bind control port 127.0.0.1:%d: %s\n", ctrl_port, strerror(errno));
  1237. return 1;
  1238. }
  1239. for (int i = 0; i < g_num_stations; i++) {
  1240. pthread_t t_ipmi, t_ssh, t_uart, t_p22;
  1241. pthread_create(&t_ipmi, NULL, ipmi_udp_worker, &g_stations[i]);
  1242. pthread_detach(t_ipmi);
  1243. pthread_create(&t_ssh, NULL, ssh_console_worker, &g_stations[i]);
  1244. pthread_detach(t_ssh);
  1245. pthread_create(&t_uart, NULL, uart_bridge_worker, &g_stations[i]);
  1246. pthread_detach(t_uart);
  1247. if (g_stations[i].probe22_port > 0) {
  1248. pthread_create(&t_p22, NULL, tcp_probe22_worker, &g_stations[i]);
  1249. pthread_detach(t_p22);
  1250. }
  1251. }
  1252. printf("READY ctrl=127.0.0.1:%d stations=%d\n", ctrl_port, g_num_stations);
  1253. fflush(stdout);
  1254. while (g_running) {
  1255. struct pollfd pfd = { .fd = ctrl_lfd, .events = POLLIN, .revents = 0 };
  1256. if (poll(&pfd, 1, 100) <= 0) continue;
  1257. int cfd = accept(ctrl_lfd, NULL, NULL);
  1258. if (cfd < 0) continue;
  1259. char lbuf[1024];
  1260. ssize_t n = recv(cfd, lbuf, sizeof(lbuf) - 1, 0);
  1261. if (n > 0) {
  1262. lbuf[n] = '\0';
  1263. handle_ctrl_line(cfd, lbuf);
  1264. }
  1265. close(cfd);
  1266. }
  1267. close(ctrl_lfd);
  1268. unlink(g_hostkey_path);
  1269. ssh_finalize();
  1270. return 0;
  1271. }