xref: /freebsd/usr.sbin/boot0cfg/boot0cfg.c (revision 4007d914e7973bca8ac488ab50aca56964eed90f)
1 /*
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2008 Luigi Rizzo
5  * Copyright (c) 1999 Robert Nordier
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
21  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
22  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
23  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
26  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
27  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <sys/param.h>
31 #include <sys/disklabel.h>
32 #include <sys/diskmbr.h>
33 #include <sys/stat.h>
34 
35 #include <err.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <libgeom.h>
39 #include <paths.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 
45 #define MBRSIZE         512     /* master boot record size */
46 
47 #define OFF_VERSION	0x1b0	/* offset: version number, only boot0version */
48 #define OFF_SERIAL	0x1b8	/* offset: volume serial number */
49 #define OFF_PTBL        0x1be   /* offset: partition table */
50 #define OFF_MAGIC       0x1fe   /* offset: magic number */
51 /*
52  * Offsets to the parameters of the 512-byte boot block.
53  * For historical reasons they are set as macros
54  */
55 struct opt_offsets {
56 	int opt;
57 	int drive;
58 	int flags;
59 	int ticks;
60 };
61 
62 static struct opt_offsets b0_ofs[] = {
63 	{ 0x0, 0x0, 0x0, 0x0 },		/* no boot block */
64 	{ 0x1b9, 0x1ba, 0x1bb, 0x1bc },	/* original block */
65 	{ 0x1b5, 0x1b6, 0x1b7, 0x1bc },	/* NT_SERIAL block */
66 };
67 
68 static int b0_ver;	/* boot block version set by boot0bs */
69 
70 #define OFF_OPT		(b0_ofs[b0_ver].opt)	/* default boot option */
71 #define OFF_DRIVE	(b0_ofs[b0_ver].drive)	/* setdrv drive */
72 #define OFF_FLAGS       (b0_ofs[b0_ver].flags)	/* option flags */
73 #define OFF_TICKS       (b0_ofs[b0_ver].ticks)	/* clock ticks */
74 
75 
76 #define cv2(p)  ((p)[0] | (p)[1] << 010)
77 
78 #define mk2(p, x)                               \
79     (p)[0] = (u_int8_t)(x),                     \
80     (p)[1] = (u_int8_t)((x) >> 010)
81 
82 static const struct {
83     const char *tok;
84     int def;
85 } opttbl[] = {
86     {"packet", 0},
87     {"update", 1},
88     {"setdrv", 0}
89 };
90 static const int nopt = nitems(opttbl);
91 
92 static const char fmt0[] = "#   flag     start chs   type"
93     "       end chs       offset         size\n";
94 
95 static const char fmt1[] = "%d   0x%02x   %4u:%3u:%2u   0x%02x"
96     "   %4u:%3u:%2u   %10u   %10u\n";
97 
98 static int geom_class_available(const char *);
99 static int read_mbr(const char *, u_int8_t **, int);
100 static void write_mbr(const char *, int, u_int8_t *, int, int);
101 static void display_mbr(u_int8_t *);
102 static int boot0version(const u_int8_t *);
103 static int boot0bs(const u_int8_t *);
104 static void stropt(const char *, int *, int *);
105 static int argtoi(const char *, int, int, int);
106 static int set_bell(u_int8_t *, int, int);
107 static void usage(void) __dead2;
108 
109 static unsigned vol_id[5];	/* 4 plus 1 for flag */
110 
111 static int v_flag;
112 /*
113  * Boot manager installation/configuration utility.
114  */
115 int
main(int argc,char * argv[])116 main(int argc, char *argv[])
117 {
118     struct stat sb;
119     u_int8_t *mbr, *boot0;
120     int boot0_size, mbr_size;
121     const char *bpath, *fpath;
122     char *disk;
123     int B_flag, o_flag;
124     int d_arg, m_arg, s_arg, t_arg;
125     int o_and, o_or, o_e = -1;
126     int up, c;
127 
128     bpath = "/boot/boot0";
129     fpath = NULL;
130     B_flag = v_flag = o_flag = 0;
131     d_arg = m_arg = s_arg = t_arg = -1;
132     o_and = 0xff;
133     o_or = 0;
134     while ((c = getopt(argc, argv, "Bvb:d:e:f:i:m:o:s:t:")) != -1)
135         switch (c) {
136         case 'B':
137             B_flag = 1;
138             break;
139         case 'v':
140             v_flag = 1;
141             break;
142         case 'b':
143             bpath = optarg;
144             break;
145         case 'd':
146             d_arg = argtoi(optarg, 0, 0xff, 'd');
147             break;
148         case 'e':
149 	    if (optarg[0] == '0' && optarg[1] == 'x')
150 		sscanf(optarg, "0x%02x", &o_e);
151 	    else
152 		o_e = optarg[0];
153             break;
154         case 'f':
155             fpath = optarg;
156             break;
157         case 'i':
158             if (sscanf(optarg, "%02x%02x-%02x%02x",
159 		vol_id, vol_id+1, vol_id+2, vol_id+3) == 4)
160 			vol_id[4] = 1;
161 	    else
162 		errx(1, "bad argument %s", optarg);
163             break;
164         case 'm':
165             m_arg = argtoi(optarg, 0, 0xf, 'm');
166             break;
167         case 'o':
168             stropt(optarg, &o_and, &o_or);
169             o_flag = 1;
170             break;
171         case 's':
172 	    if (strcasecmp(optarg, "pxe") == 0)
173 		s_arg = 6;
174 	    else
175 		s_arg = argtoi(optarg, 1, 6, 's');
176             break;
177         case 't':
178             t_arg = argtoi(optarg, 1, 0xffff, 't');
179             break;
180         default:
181             usage();
182         }
183     argc -= optind;
184     argv += optind;
185     if (argc != 1)
186         usage();
187     if (stat(*argv, &sb) == 0 && S_ISREG(sb.st_mode)) {
188         disk = strdup(*argv);
189         if (disk == NULL)
190             err(1, "strdup");
191     } else {
192         disk = g_device_path(*argv);
193         if (disk == NULL)
194             errx(1, "Unable to get providername for %s\n", *argv);
195     }
196     up = B_flag || d_arg != -1 || m_arg != -1 || o_flag || s_arg != -1
197 	|| t_arg != -1;
198 
199     /* open the disk and read in the existing mbr. Either here or
200      * when reading the block from disk, we do check for the version
201      * and abort if a suitable block is not found.
202      */
203     mbr_size = read_mbr(disk, &mbr, !B_flag);
204 
205     /* save the existing MBR if we are asked to do so */
206     if (fpath)
207 	write_mbr(fpath, O_CREAT | O_TRUNC, mbr, mbr_size, 0);
208 
209     /*
210      * If we are installing the boot loader, read it from disk and copy the
211      * slice table over from the existing MBR.  If not, then point boot0
212      * back at the MBR we just read in.  After this, boot0 is the data to
213      * write back to disk if we are going to do a write.
214      */
215     if (B_flag) {
216 	boot0_size = read_mbr(bpath, &boot0, 1);
217         memcpy(boot0 + OFF_PTBL, mbr + OFF_PTBL,
218 	    sizeof(struct dos_partition) * NDOSPART);
219 	if (b0_ver == 2)	/* volume serial number support */
220 	    memcpy(boot0 + OFF_SERIAL, mbr + OFF_SERIAL, 4);
221     } else {
222 	boot0 = mbr;
223 	boot0_size = mbr_size;
224     }
225 
226     /* set the drive */
227     if (d_arg != -1)
228 	boot0[OFF_DRIVE] = d_arg;
229 
230     /* set various flags */
231     if (m_arg != -1) {
232 	boot0[OFF_FLAGS] &= 0xf0;
233 	boot0[OFF_FLAGS] |= m_arg;
234     }
235     if (o_flag) {
236         boot0[OFF_FLAGS] &= o_and;
237         boot0[OFF_FLAGS] |= o_or;
238     }
239 
240     /* set the default boot selection */
241     if (s_arg != -1)
242         boot0[OFF_OPT] = s_arg - 1;
243 
244     /* set the timeout */
245     if (t_arg != -1)
246         mk2(boot0 + OFF_TICKS, t_arg);
247 
248     /* set the bell char */
249     if (o_e != -1 && set_bell(boot0, o_e, 0) != -1)
250 	up = 1;
251 
252     if (vol_id[4]) {
253 	if (b0_ver != 2)
254 	    errx(1, "incompatible boot block, cannot set volume ID");
255 	boot0[OFF_SERIAL] = vol_id[0];
256 	boot0[OFF_SERIAL+1] = vol_id[1];
257 	boot0[OFF_SERIAL+2] = vol_id[2];
258 	boot0[OFF_SERIAL+3] = vol_id[3];
259 	up = 1;	/* force update */
260     }
261     /* write the MBR back to disk */
262     if (up)
263 	write_mbr(disk, 0, boot0, boot0_size, vol_id[4] || b0_ver == 1);
264 
265     /* display the MBR */
266     if (v_flag)
267 	display_mbr(boot0);
268 
269     /* clean up */
270     if (mbr != boot0)
271 	free(boot0);
272     free(mbr);
273     free(disk);
274 
275     return 0;
276 }
277 
278 /* get or set the 'bell' character to be used in case of errors.
279  * Lookup for a certain code sequence, return -1 if not found.
280  */
281 static int
set_bell(u_int8_t * mbr,int new_bell,int report)282 set_bell(u_int8_t *mbr, int new_bell, int report)
283 {
284     /* lookup sequence: 0x100 means skip, 0x200 means done */
285     static unsigned seq[] =
286 		{ 0xb0, 0x100, 0xe8, 0x100, 0x100, 0x30, 0xe4, 0x200 };
287     int ofs, i, c;
288     for (ofs = 0x60; ofs < 0x180; ofs++) { /* search range */
289 	if (mbr[ofs] != seq[0])	/* search initial pattern */
290 	    continue;
291 	for (i=0;; i++) {
292 	    if (seq[i] == 0x200) {	/* found */
293 		c = mbr[ofs+1];
294 		if (!report)
295 		    mbr[ofs+1] = c = new_bell;
296 		else
297 		    printf("  bell=%c (0x%x)",
298 			(c >= ' ' && c < 0x7f) ? c : ' ', c);
299 		return c;
300 	    }
301 	    if (seq[i] != 0x100 && seq[i] != mbr[ofs+i])
302 		break;
303 	}
304     }
305     warn("bell not found");
306     return -1;
307 }
308 /*
309  * Read in the MBR of the disk.  If it is boot0, then use the version to
310  * read in all of it if necessary.  Use pointers to return a malloc'd
311  * buffer containing the MBR and then return its size.
312  */
313 static int
read_mbr(const char * disk,u_int8_t ** mbr,int check_version)314 read_mbr(const char *disk, u_int8_t **mbr, int check_version)
315 {
316     u_int8_t buf[MBRSIZE];
317     int mbr_size, fd;
318     int ver;
319     ssize_t n;
320 
321     if ((fd = open(disk, O_RDONLY)) == -1)
322         err(1, "open %s", disk);
323     if ((n = read(fd, buf, MBRSIZE)) == -1)
324         err(1, "read %s", disk);
325     if (n != MBRSIZE)
326         errx(1, "%s: short read", disk);
327     if (cv2(buf + OFF_MAGIC) != 0xaa55)
328         errx(1, "%s: bad magic", disk);
329 
330     if (! (ver = boot0bs(buf))) {
331 	if (check_version)
332 	    errx(1, "%s: unknown or incompatible boot code", disk);
333     } else if (boot0version(buf) == 0x101) {
334 	mbr_size = 1024;
335 	if ((*mbr = malloc(mbr_size)) == NULL)
336 	    errx(1, "%s: unable to allocate read buffer", disk);
337 	if (lseek(fd, 0, SEEK_SET) == -1 ||
338 	    (n = read(fd, *mbr, mbr_size)) == -1)
339 	    err(1, "%s", disk);
340 	if (n != mbr_size)
341 	    errx(1, "%s: short read", disk);
342 	close(fd);
343 	return (mbr_size);
344     }
345     if ((*mbr = malloc(sizeof(buf))) == NULL)
346 	errx(1, "%s: unable to allocate MBR buffer", disk);
347     memcpy(*mbr, buf, sizeof(buf));
348     close(fd);
349 
350     return sizeof(buf);
351 }
352 
353 static int
geom_class_available(const char * name)354 geom_class_available(const char *name)
355 {
356 	struct gclass *class;
357 	struct gmesh mesh;
358 	int error;
359 
360 	error = geom_gettree(&mesh);
361 	if (error != 0)
362 		errc(1, error, "Cannot get GEOM tree");
363 
364 	LIST_FOREACH(class, &mesh.lg_class, lg_class) {
365 		if (strcmp(class->lg_name, name) == 0) {
366 			geom_deletetree(&mesh);
367 			return (1);
368 		}
369 	}
370 
371 	geom_deletetree(&mesh);
372 	return (0);
373 }
374 
375 /*
376  * Write out the mbr to the specified file.
377  */
378 static void
write_mbr(const char * fname,int flags,u_int8_t * mbr,int mbr_size,int disable_dsn)379 write_mbr(const char *fname, int flags, u_int8_t *mbr, int mbr_size,
380     int disable_dsn)
381 {
382 	struct gctl_req *grq;
383 	struct stat sb;
384 	const char *errmsg;
385 	char *pname;
386 	ssize_t n;
387 	int fd;
388 
389 	fd = open(fname, O_WRONLY | flags, 0666);
390 	if (fd != -1) {
391 		n = write(fd, mbr, mbr_size);
392 		close(fd);
393 		if (n != mbr_size)
394 			errx(1, "%s: short write", fname);
395 		return;
396 	}
397 
398 	/*
399 	 * If we're called to write to a backup file, don't try to
400 	 * write through GEOM.
401 	 */
402 	if (flags != 0)
403 		err(1, "can't open file %s to write backup", fname);
404 
405 	/*
406 	 * Try to open it read only to pass to GEOM,
407 	 * or inspect if it's a regular file.
408 	 */
409 	fd = open(fname, O_RDONLY);
410 	if (fd == -1) {
411 		warn("error opening %s", fname);
412 		return;
413 	}
414 
415 	/*
416 	 * If name is a regular file, re-open it in write-only mode
417 	 * and write the MBR straight to it.
418 	 */
419 	if (fstat(fd, &sb) == 0 && S_ISREG(sb.st_mode)) {
420 		close(fd);
421 		fd = open(fname, O_WRONLY);
422 		if (fd == -1)
423 			err(1, "can't open %s for writing", fname);
424 		n = write(fd, mbr, mbr_size);
425 		close(fd);
426 		if (n != mbr_size)
427 			errx(1, "%s: short write", fname);
428 		return;
429 	}
430 
431 	pname = g_providername(fd);
432 	close(fd);
433 	if (pname == NULL) {
434 		warn("error getting providername for %s", fname);
435 		return;
436 	}
437 
438 	/* Check that GEOM_PART is available */
439 	if (geom_class_available("PART") != 0) {
440 		grq = gctl_get_handle();
441 		gctl_ro_param(grq, "class", -1, "PART");
442 		gctl_ro_param(grq, "arg0", -1, pname);
443 		gctl_ro_param(grq, "verb", -1, "bootcode");
444 		gctl_ro_param(grq, "bootcode", mbr_size, mbr);
445 		gctl_ro_param(grq, "flags", -1, "C");
446 		if (disable_dsn)
447 			gctl_ro_param(grq, "skip_dsn", sizeof(int),
448 			    &disable_dsn);
449 		errmsg = gctl_issue(grq);
450 		if (errmsg != NULL && errmsg[0] != '\0')
451 			errx(1, "GEOM_PART: write bootcode to %s failed: %s",
452 			    fname, errmsg);
453 		gctl_free(grq);
454 	} else
455 		errx(1, "can't write MBR to %s", fname);
456 	free(pname);
457 }
458 
459 /*
460  * Outputs an informative dump of the data in the MBR to stdout.
461  */
462 static void
display_mbr(u_int8_t * mbr)463 display_mbr(u_int8_t *mbr)
464 {
465     struct dos_partition *part;
466     int i, version;
467 
468     part = (struct dos_partition *)(mbr + DOSPARTOFF);
469     printf(fmt0);
470     for (i = 0; i < NDOSPART; i++)
471 	if (part[i].dp_typ)
472 	    printf(fmt1, 1 + i, part[i].dp_flag,
473 		part[i].dp_scyl + ((part[i].dp_ssect & 0xc0) << 2),
474 		part[i].dp_shd, part[i].dp_ssect & 0x3f, part[i].dp_typ,
475                 part[i].dp_ecyl + ((part[i].dp_esect & 0xc0) << 2),
476                 part[i].dp_ehd, part[i].dp_esect & 0x3f, part[i].dp_start,
477                 part[i].dp_size);
478     printf("\n");
479     version = boot0version(mbr);
480     printf("version=%d.%d  drive=0x%x  mask=0x%x  ticks=%u",
481 	version >> 8, version & 0xff, mbr[OFF_DRIVE],
482 	mbr[OFF_FLAGS] & 0xf, cv2(mbr + OFF_TICKS));
483     set_bell(mbr, 0, 1);
484     printf("\noptions=");
485     for (i = 0; i < nopt; i++) {
486 	if (i)
487 	    printf(",");
488 	if (!(mbr[OFF_FLAGS] & 1 << (7 - i)) ^ opttbl[i].def)
489 	    printf("no");
490 	printf("%s", opttbl[i].tok);
491     }
492     printf("\n");
493     if (b0_ver == 2)
494 	printf("volume serial ID %02x%02x-%02x%02x\n",
495 		mbr[OFF_SERIAL], mbr[OFF_SERIAL+1],
496 		mbr[OFF_SERIAL+2], mbr[OFF_SERIAL+3]);
497     printf("default_selection=F%d (", mbr[OFF_OPT] + 1);
498     if (mbr[OFF_OPT] < 4)
499 	printf("Slice %d", mbr[OFF_OPT] + 1);
500     else if (mbr[OFF_OPT] == 4)
501 	printf("Drive 1");
502     else
503 	printf("PXE");
504     printf(")\n");
505 }
506 
507 /*
508  * Return the boot0 version with the minor revision in the low byte, and
509  * the major revision in the next higher byte.
510  */
511 static int
boot0version(const u_int8_t * bs)512 boot0version(const u_int8_t *bs)
513 {
514     /* Check for old version, and return 0x100 if found. */
515     int v = boot0bs(bs);
516     if (v != 0)
517         return v << 8;
518 
519     /* We have a newer boot0, so extract the version number and return it. */
520     return *(const int *)(bs + OFF_VERSION) & 0xffff;
521 }
522 
523 /* descriptor of a pattern to match.
524  * Start from the first entry trying to match the chunk of bytes,
525  * if you hit an entry with len=0 terminate the search and report
526  * off as the version. Otherwise skip to the next block after len=0
527  * An entry with len=0, off=0 is the end marker.
528   */
529 struct byte_pattern {
530     unsigned off;
531     unsigned len;
532     u_int8_t *key;
533 };
534 
535 /*
536  * Decide if we have valid boot0 boot code by looking for
537  * characteristic byte sequences at fixed offsets.
538  */
539 static int
boot0bs(const u_int8_t * bs)540 boot0bs(const u_int8_t *bs)
541 {
542     /* the initial code sequence */
543     static u_int8_t id0[] = {0xfc, 0x31, 0xc0, 0x8e, 0xc0, 0x8e, 0xd8,
544 			     0x8e, 0xd0, 0xbc, 0x00, 0x7c };
545     /* the drive id */
546     static u_int8_t id1[] = {'D', 'r', 'i', 'v', 'e', ' '};
547     static struct byte_pattern patterns[] = {
548         {0x0,   sizeof(id0), id0},
549         {0x1b2, sizeof(id1), id1},
550         {1, 0, NULL},
551         {0x0,   sizeof(id0), id0},	/* version with NT support */
552         {0x1ae, sizeof(id1), id1},
553         {2, 0, NULL},
554         {0, 0, NULL},
555     };
556     struct byte_pattern *p = patterns;
557 
558     for (;  p->off || p->len; p++) {
559 	if (p->len == 0)
560 	    break;
561 	if (!memcmp(bs + p->off, p->key, p->len))	/* match */
562 	    continue;
563 	while (p->len)	/* skip to next block */
564 	    p++;
565     }
566     b0_ver = p->off;	/* XXX ugly side effect */
567     return p->off;
568 }
569 
570 /*
571  * Adjust "and" and "or" masks for a -o option argument.
572  */
573 static void
stropt(const char * arg,int * xa,int * xo)574 stropt(const char *arg, int *xa, int *xo)
575 {
576     const char *q;
577     char *s, *s1;
578     int inv, i, x;
579 
580     if (!(s = strdup(arg)))
581         err(1, NULL);
582     for (s1 = s; (q = strtok(s1, ",")); s1 = NULL) {
583         if ((inv = !strncmp(q, "no", 2)))
584             q += 2;
585         for (i = 0; i < nopt; i++)
586             if (!strcmp(q, opttbl[i].tok))
587                 break;
588         if (i == nopt)
589             errx(1, "%s: Unknown -o option", q);
590         if (opttbl[i].def)
591             inv ^= 1;
592         x = 1 << (7 - i);
593         if (inv)
594             *xa &= ~x;
595         else
596             *xo |= x;
597     }
598     free(s);
599 }
600 
601 /*
602  * Convert and check an option argument.
603  */
604 static int
argtoi(const char * arg,int lo,int hi,int opt)605 argtoi(const char *arg, int lo, int hi, int opt)
606 {
607     char *s;
608     long x;
609 
610     errno = 0;
611     x = strtol(arg, &s, 0);
612     if (errno || !*arg || *s || x < lo || x > hi)
613         errx(1, "%s: Bad argument to -%c option", arg, opt);
614     return x;
615 }
616 
617 /*
618  * Display usage information.
619  */
620 static void
usage(void)621 usage(void)
622 {
623     fprintf(stderr, "%s\n%s\n",
624     "usage: boot0cfg [-Bv] [-b boot0] [-d drive] [-f file] [-m mask]",
625     "                [-o options] [-s slice] [-t ticks] disk | file");
626     exit(1);
627 }
628