nvmutil.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /* SPDX-License-Identifier: MIT */
  2. /* Copyright (c) 2022-2025 Leah Rowe <leah@libreboot.org> */
  3. /* Copyright (c) 2023 Riku Viitanen <riku.viitanen@protonmail.com> */
  4. #include <sys/stat.h>
  5. #include <dirent.h>
  6. #include <err.h>
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <stdint.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14. void cmd_setchecksum(void), cmd_brick(void), swap(int partnum), writeGbe(void),
  15. cmd_dump(void), cmd_setmac(void), readGbe(void), checkdir(const char *path),
  16. macf(int partnum), hexdump(int partnum), openFiles(const char *path),
  17. cmd_copy(void), parseMacString(const char *strMac, uint16_t *mac),
  18. cmd_swap(void);
  19. int goodChecksum(int partnum);
  20. uint8_t hextonum(char chs), rhex(void);
  21. #define COMMAND argv[2]
  22. #define MAC_ADDRESS argv[3]
  23. #define PARTN argv[3]
  24. #define NVM_CHECKSUM 0xBABA /* checksum value */
  25. #define NVM_CHECKSUM_WORD 0x3F /* checksum word position */
  26. #define NVM_SIZE 128 /* Area containing NVM words */
  27. #define SIZE_4KB 0x1000
  28. #define SIZE_8KB 0x2000
  29. #define SIZE_16KB 0x4000
  30. #define SIZE_128KB 0x20000
  31. uint16_t mac[3] = {0, 0, 0};
  32. ssize_t nf;
  33. size_t partsize, gbe[2];
  34. uint8_t nvmPartChanged[2] = {0, 0}, do_read[2] = {1, 1};
  35. int flags, rfd, fd, part;
  36. const char *strMac = NULL, *strRMac = "??:??:??:??:??:??", *filename = NULL;
  37. /* available commands, set a pointer based on user command */
  38. typedef struct op {
  39. char *str;
  40. void (*cmd)(void);
  41. int args;
  42. } op_t;
  43. op_t op[] = {
  44. { .str = "dump", .cmd = cmd_dump, .args = 3},
  45. { .str = "setmac", .cmd = cmd_setmac, .args = 3},
  46. { .str = "swap", .cmd = cmd_swap, .args = 3},
  47. { .str = "copy", .cmd = cmd_copy, .args = 4},
  48. { .str = "brick", .cmd = cmd_brick, .args = 4},
  49. { .str = "setchecksum", .cmd = cmd_setchecksum, .args = 4},
  50. };
  51. void (*cmd)(void) = NULL;
  52. /* wrappers for BSD-style err() function (error handling) */
  53. #define ERR() errno = errno ? errno : ECANCELED
  54. #define err_if(x) if (x) err(ERR(), "%s", filename)
  55. /* Macro for opening a file with errors properly handled */
  56. #define xopen(f,l,p) if ((f = open(l, p)) == -1) err(ERR(), "%s", l); \
  57. if (fstat(f, &st) == -1) err(ERR(), "%s", l)
  58. /* Macros for reading/writing the GbE file in memory */
  59. #define word(pos16, partnum) ((uint16_t *) gbe[partnum])[pos16]
  60. #define setWord(pos16, p, val16) if (word(pos16, p) != val16) \
  61. nvmPartChanged[p] = 1 | (word(pos16, p) = val16)
  62. int
  63. main(int argc, char *argv[])
  64. {
  65. #ifdef __OpenBSD__
  66. /* OpenBSD pledge (sandboxing): https://man.openbsd.org/pledge.2 */
  67. err_if(pledge("stdio rpath wpath unveil", NULL) == -1);
  68. #endif
  69. if (argc < 2) { /* TODO: manpage! */
  70. fprintf(stderr, "Modify Intel GbE NVM images e.g. set MAC\n");
  71. fprintf(stderr, "USAGE:\n");
  72. fprintf(stderr, " %s FILE dump\n", argv[0]);
  73. fprintf(stderr, " %s FILE\n # same as setmac without arg\n",
  74. argv[0]);
  75. fprintf(stderr, " %s FILE setmac [MAC]\n", argv[0]);
  76. fprintf(stderr, " %s FILE swap\n", argv[0]);
  77. fprintf(stderr, " %s FILE copy 0|1\n", argv[0]);
  78. fprintf(stderr, " %s FILE brick 0|1\n", argv[0]);
  79. fprintf(stderr, " %s FILE setchecksum 0|1\n", argv[0]);
  80. err(errno = ECANCELED, "Too few arguments");
  81. }
  82. filename = argv[1];
  83. flags = O_RDWR;
  84. if (argc > 2) {
  85. if (strcmp(COMMAND, "dump") == 0) {
  86. flags = O_RDONLY; /* write not needed for dump cmd */
  87. #ifdef __OpenBSD__
  88. /* writes not needed for the dump command */
  89. err_if(pledge("stdio rpath unveil", NULL) == -1);
  90. #endif
  91. }
  92. }
  93. /* check for dir first, to prevent unveil from
  94. permitting directory access on OpenBSD */
  95. checkdir("/dev/urandom");
  96. checkdir(filename); /* Must be a file, not a directory */
  97. #ifdef __OpenBSD__
  98. /* OpenBSD unveil: https://man.openbsd.org/unveil.2 */
  99. err_if(unveil("/dev/urandom", "r") == -1);
  100. /* Only allow access to /dev/urandom and the gbe file */
  101. if (flags == O_RDONLY) { /* dump command */
  102. err_if(unveil(filename, "r") == -1); /* write not needed */
  103. err_if(unveil(NULL, NULL) == -1); /* lock unveil */
  104. err_if(pledge("stdio rpath", NULL) == -1); /* lock unveil */
  105. } else { /* other commands need read-write */
  106. err_if(unveil(filename, "rw") == -1);
  107. err_if(unveil(NULL, NULL) == -1); /* lock unveil */
  108. err_if(pledge("stdio rpath wpath", NULL) == -1); /* no unveil */
  109. }
  110. #endif
  111. openFiles(filename); /* open files first, to allow harder pledge: */
  112. #ifdef __OpenBSD__
  113. /* OpenBSD sandboxing: https://man.openbsd.org/pledge.2 */
  114. err_if(pledge("stdio", NULL) == -1);
  115. #endif
  116. if (argc > 2) {
  117. for (int i = 0; (i < 6) && (cmd == NULL); i++) {
  118. if (strcmp(COMMAND, op[i].str) != 0)
  119. continue;
  120. if (argc >= op[i].args) {
  121. cmd = op[i].cmd;
  122. break;
  123. }
  124. err(errno = EINVAL, "Too few args on command '%s'",
  125. op[i].str);
  126. }
  127. } else {
  128. cmd = cmd_setmac;
  129. }
  130. if ((cmd == NULL) && (argc > 2)) { /* nvm gbe [MAC] */
  131. strMac = COMMAND;
  132. cmd = cmd_setmac;
  133. } else if (cmd == cmd_setmac) { /* nvm gbe setmac [MAC] */
  134. strMac = strRMac; /* random MAC */
  135. if (argc > 3) /* user-supplied MAC (can be random) */
  136. strMac = MAC_ADDRESS;
  137. } else if ((cmd != NULL) && (argc > 3)) { /* user-supplied partnum */
  138. err_if((errno = (!((part = PARTN[0] - '0') == 0 || part == 1))
  139. || PARTN[1] ? EINVAL : errno)); /* only allow '0' or '1' */
  140. }
  141. err_if((errno = (cmd == NULL) ? EINVAL : errno)); /* bad user arg */
  142. readGbe(); /* read gbe file into memory */
  143. (*cmd)(); /* operate on gbe file in memory */
  144. writeGbe(); /* write changes back to file */
  145. err_if((errno != 0) && (cmd != cmd_dump)); /* don't err on dump */
  146. return errno; /* errno can be set by the dump command */
  147. }
  148. /*
  149. * check whether urandom/file is a directory, and err if so,
  150. * to prevent later unveil calls from permitting directory access
  151. * on OpenBSD
  152. */
  153. void
  154. checkdir(const char *path)
  155. {
  156. if (opendir(path) != NULL)
  157. err(errno = EISDIR, "%s", path);
  158. if (errno == ENOTDIR)
  159. errno = 0;
  160. err_if(errno);
  161. }
  162. /* open gbe file and /dev/urandom, setting permissions */
  163. void
  164. openFiles(const char *path)
  165. {
  166. struct stat st;
  167. xopen(fd, path, flags); /* gbe file */
  168. switch(st.st_size) {
  169. case SIZE_8KB:
  170. case SIZE_16KB:
  171. case SIZE_128KB:
  172. partsize = st.st_size >> 1;
  173. break;
  174. default:
  175. err(errno = ECANCELED, "Invalid file size (not 8/16/128KiB)");
  176. break;
  177. }
  178. /* the MAC address randomiser relies on reading urandom */
  179. xopen(rfd, "/dev/urandom", O_RDONLY);
  180. }
  181. /* read gbe file into memory buffer */
  182. void
  183. readGbe(void)
  184. {
  185. if ((cmd == cmd_swap) || (cmd == cmd_copy))
  186. nf = SIZE_4KB; /* read/write the entire block */
  187. /* only need to do 4KB even on larger gbe files */
  188. else
  189. nf = NVM_SIZE; /* only read/write the nvm part of the block */
  190. if ((cmd == cmd_copy) || (cmd == cmd_setchecksum) || (cmd == cmd_brick))
  191. do_read[part ^ 1] = 0; /* only read the user-specified part */
  192. /* AND do_read[*] to avoid wasteful malloc */
  193. /* cmd_copy also relies on this */
  194. char *buf = malloc(nf << (do_read[0] & do_read[1]));
  195. if (buf == NULL)
  196. err(errno, NULL);
  197. /* we pread per-part, so each part has its own pointer: */
  198. /* if a do_read is 0, both pointers are the same; this accomplishes
  199. the desired result for cmd_copy (see cmd_copy function) */
  200. gbe[0] = (size_t) buf;
  201. gbe[1] = gbe[0] + (nf * (do_read[0] & do_read[1]));
  202. ssize_t tnr = 0; /* total bytes read */
  203. for (int p = 0; p < 2; p++) {
  204. if (!do_read[p])
  205. continue; /* avoid unnecessary reads */
  206. ssize_t nr = pread(fd, (uint8_t *) gbe[p], nf, p * partsize);
  207. err_if(nr == -1);
  208. if (nr != nf)
  209. err(errno == ECANCELED,
  210. "%ld bytes written on '%s', expected %ld bytes\n",
  211. nr, filename, nf);
  212. tnr += nr;
  213. swap(p); /* handle big-endian host CPU */
  214. }
  215. printf("%ld bytes read from file '%s'\n", tnr, filename);
  216. }
  217. /* set MAC address and checksum on nvm part */
  218. void
  219. cmd_setmac(void)
  220. {
  221. int mac_updated = 0;
  222. parseMacString(strMac, mac);
  223. printf("MAC address to be written: %s\n", strMac);
  224. for (int partnum = 0; partnum < 2; partnum++) {
  225. if (!goodChecksum(part = partnum))
  226. continue;
  227. for (int w = 0; w < 3; w++) /* write MAC to gbe part */
  228. setWord(w, partnum, mac[w]);
  229. printf("Wrote MAC address to part %d: ", partnum);
  230. macf(partnum);
  231. cmd_setchecksum(); /* MAC updated; need valid checksum */
  232. mac_updated = 1;
  233. }
  234. if (mac_updated)
  235. errno = 0; /* reset in case one of the checksums failed */
  236. }
  237. /* parse MAC string, write to char buffer */
  238. void
  239. parseMacString(const char *strMac, uint16_t *mac)
  240. {
  241. uint64_t total = 0;
  242. if (strnlen(strMac, 20) != 17)
  243. err(errno = EINVAL, "Invalid MAC address string length");
  244. for (uint8_t h, i = 0; i < 16; i += 3) {
  245. if (i != 15)
  246. if (strMac[i + 2] != ':')
  247. err(errno = EINVAL,
  248. "Invalid MAC address separator '%c'",
  249. strMac[i + 2]);
  250. int byte = i / 3;
  251. /* Update MAC buffer per-nibble from a given string */
  252. for (int nib = 0; nib < 2; nib++, total += h) {
  253. if ((h = hextonum(strMac[i + nib])) > 15)
  254. err(errno = EINVAL, "Invalid character '%c'",
  255. strMac[i + nib]);
  256. /* if random: ensure local-only, unicast MAC */
  257. if ((byte == 0) && (nib == 1)) /* unicast/local nib */
  258. if (strMac[i + nib] == '?') /* ?=random */
  259. h = (h & 0xE) | 2; /* local, unicast */
  260. mac[byte >> 1] |= ((uint16_t ) h)
  261. << ((8 * (byte % 2)) + (4 * (nib ^ 1)));
  262. }
  263. }
  264. if (total == 0)
  265. err(errno = EINVAL, "Invalid MAC (all-zero MAC address)");
  266. if (mac[0] & 1)
  267. err(errno = EINVAL, "Invalid MAC (multicast bit set)");
  268. }
  269. /* convert hex char to char value (0-15) */
  270. uint8_t
  271. hextonum(char ch)
  272. {
  273. if ((ch >= '0') && (ch <= '9'))
  274. return ch - '0';
  275. else if ((ch >= 'A') && (ch <= 'F'))
  276. return ch - 'A' + 10;
  277. else if ((ch >= 'a') && (ch <= 'f'))
  278. return ch - 'a' + 10;
  279. return (ch == '?') ? rhex() : 16; /* 16 for error (invalid char) */
  280. }
  281. /* random number generator */
  282. uint8_t
  283. rhex(void)
  284. {
  285. static uint8_t n = 0, rnum[16];
  286. if (!n)
  287. err_if(pread(rfd, (uint8_t *) &rnum, (n = 15) + 1, 0) == -1);
  288. return rnum[n--] & 0xf;
  289. }
  290. /* print mac address and hexdump of parts */
  291. void
  292. cmd_dump(void)
  293. {
  294. for (int partnum = 0, numInvalid = 0; partnum < 2; partnum++) {
  295. if ((cmd != cmd_dump) && (flags != O_RDONLY) &&
  296. (!nvmPartChanged[partnum]))
  297. continue;
  298. if (!goodChecksum(partnum))
  299. ++numInvalid;
  300. printf("MAC (part %d): ", partnum);
  301. macf(partnum);
  302. hexdump(partnum);
  303. if ((numInvalid < 2) && (partnum))
  304. errno = 0;
  305. }
  306. }
  307. /* print mac address of part */
  308. void
  309. macf(int partnum)
  310. {
  311. for (int c = 0; c < 3; c++) {
  312. uint16_t val16 = word(c, partnum);
  313. printf("%02x:%02x", val16 & 0xff, val16 >> 8);
  314. if (c == 2)
  315. printf("\n");
  316. else
  317. printf(":");
  318. }
  319. }
  320. /* print hexdump of nvm part */
  321. void
  322. hexdump(int partnum)
  323. {
  324. for (int row = 0; row < 8; row++) {
  325. printf("%08x ", row << 4);
  326. for (int c = 0; c < 8; c++) {
  327. uint16_t val16 = word((row << 3) + c, partnum);
  328. if (c == 4)
  329. printf(" ");
  330. printf(" %02x %02x", val16 & 0xff, val16 >> 8);
  331. }
  332. printf("\n");
  333. }
  334. }
  335. /* correct the checksum on part */
  336. void
  337. cmd_setchecksum(void)
  338. {
  339. uint16_t val16 = 0;
  340. for (int c = 0; c < NVM_CHECKSUM_WORD; c++)
  341. val16 += word(c, part);
  342. /* correct the checksum */
  343. setWord(NVM_CHECKSUM_WORD, part, NVM_CHECKSUM - val16);
  344. }
  345. /* intentionally set wrong checksum on part */
  346. void
  347. cmd_brick(void)
  348. {
  349. if (goodChecksum(part))
  350. setWord(NVM_CHECKSUM_WORD, part,
  351. ((word(NVM_CHECKSUM_WORD, part)) ^ 0xFF));
  352. }
  353. /* overwrite the contents of one part with the other */
  354. void
  355. cmd_copy(void)
  356. {
  357. nvmPartChanged[part ^ 1] = goodChecksum(part);
  358. /* no need to actually copy because gbe[] pointers are both the same */
  359. /* we simply set the right nvm part as changed, and write the file */
  360. }
  361. /* swap contents between the two parts */
  362. void
  363. cmd_swap(void) {
  364. err_if(!(goodChecksum(0) || goodChecksum(1)));
  365. errno = 0;
  366. /* speedhack: swap pointers, not words. (xor swap) */
  367. gbe[0] ^= gbe[1];
  368. gbe[1] ^= gbe[0];
  369. gbe[0] ^= gbe[1];
  370. nvmPartChanged[0] = nvmPartChanged[1] = 1;
  371. }
  372. /* verify nvm part checksum (return 1 if valid) */
  373. int
  374. goodChecksum(int partnum)
  375. {
  376. uint16_t total = 0;
  377. for(int w = 0; w <= NVM_CHECKSUM_WORD; w++)
  378. total += word(w, partnum);
  379. if (total == NVM_CHECKSUM)
  380. return 1;
  381. fprintf(stderr, "WARNING: BAD checksum in part %d\n", partnum);
  382. errno = ECANCELED;
  383. return 0;
  384. }
  385. /* write the nvm parts back to the file */
  386. void
  387. writeGbe(void)
  388. {
  389. ssize_t tnw = 0; /* total bytes written */
  390. for (int p = 0; p < 2; p++) {
  391. if ((!nvmPartChanged[p]) || (flags == O_RDONLY))
  392. continue;
  393. swap(p); /* swap bytes on big-endian host CPUs */
  394. ssize_t nw = pwrite(fd, (uint8_t *) gbe[p], nf, p * partsize);
  395. err_if(nw == -1);
  396. if (nw != nf)
  397. err(errno == ECANCELED,
  398. "%ld bytes written on '%s', expected %ld bytes\n",
  399. nw, filename, nf);
  400. tnw += nf;
  401. }
  402. if ((flags != O_RDONLY) && (cmd != cmd_dump)) {
  403. if (nvmPartChanged[0] || nvmPartChanged[1])
  404. printf("The following nvm words were written:\n");
  405. cmd_dump();
  406. }
  407. if ((!tnw) && (flags != O_RDONLY) && (!errno))
  408. fprintf(stderr, "No changes needed on file '%s'\n", filename);
  409. else if (tnw)
  410. printf("%ld bytes written to file '%s'\n", tnw, filename);
  411. if (tnw)
  412. errno = 0;
  413. err_if(close(fd) == -1);
  414. }
  415. /* swap byte order on big-endian CPUs. swap skipped on little endian */
  416. void
  417. swap(int partnum) /* swaps bytes in words, not pointers. */
  418. { /* not to be confused with cmd_swap */
  419. size_t w, x;
  420. uint8_t *n = (uint8_t *) gbe[partnum];
  421. int e = 1;
  422. for (w = NVM_SIZE * ((uint8_t *) &e)[0], x = 1; w < NVM_SIZE;
  423. w += 2, x += 2) {
  424. n[w] ^= n[x];
  425. n[x] ^= n[w];
  426. n[w] ^= n[x];
  427. }
  428. }