xref: /freebsd/sbin/dumpon/dumpon.c (revision ce6a89e27cd190313be39bb479880aeda4778436)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #if 0
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1980, 1993\n\
36 	The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38 
39 #ifndef lint
40 static char sccsid[] = "From: @(#)swapon.c	8.1 (Berkeley) 6/5/93";
41 #endif /* not lint */
42 #endif
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 #include <sys/param.h>
47 #include <sys/capsicum.h>
48 #include <sys/disk.h>
49 #include <sys/socket.h>
50 #include <sys/sysctl.h>
51 
52 #include <assert.h>
53 #include <capsicum_helpers.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <ifaddrs.h>
58 #include <netdb.h>
59 #include <paths.h>
60 #include <stdbool.h>
61 #include <stdint.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <sysexits.h>
66 #include <unistd.h>
67 
68 #include <arpa/inet.h>
69 
70 #include <net/if.h>
71 #include <net/if_dl.h>
72 #include <net/route.h>
73 
74 #include <netinet/in.h>
75 #include <netinet/netdump/netdump.h>
76 
77 #ifdef HAVE_CRYPTO
78 #include <openssl/err.h>
79 #include <openssl/pem.h>
80 #include <openssl/rsa.h>
81 #endif
82 
83 static int	verbose;
84 
85 static void _Noreturn
86 usage(void)
87 {
88 	fprintf(stderr,
89     "usage: dumpon [-i index] [-r] [-v] [-k <pubkey>] [-Zz] <device>\n"
90     "       dumpon [-i index] [-r] [-v] [-k <pubkey>] [-Zz]\n"
91     "              [-g <gateway>] -s <server> -c <client> <iface>\n"
92     "       dumpon [-v] off\n"
93     "       dumpon [-v] -l\n");
94 	exit(EX_USAGE);
95 }
96 
97 /*
98  * Look for a default route on the specified interface.
99  */
100 static char *
101 find_gateway(const char *ifname)
102 {
103 	struct ifaddrs *ifa, *ifap;
104 	struct rt_msghdr *rtm;
105 	struct sockaddr *sa;
106 	struct sockaddr_dl *sdl;
107 	struct sockaddr_in *dst, *mask, *gw;
108 	char *buf, *next, *ret;
109 	size_t sz;
110 	int error, i, ifindex, mib[7];
111 
112 	/* First look up the interface index. */
113 	if (getifaddrs(&ifap) != 0)
114 		err(EX_OSERR, "getifaddrs");
115 	for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
116 		if (ifa->ifa_addr->sa_family != AF_LINK)
117 			continue;
118 		if (strcmp(ifa->ifa_name, ifname) == 0) {
119 			sdl = (struct sockaddr_dl *)(void *)ifa->ifa_addr;
120 			ifindex = sdl->sdl_index;
121 			break;
122 		}
123 	}
124 	if (ifa == NULL)
125 		errx(1, "couldn't find interface index for '%s'", ifname);
126 	freeifaddrs(ifap);
127 
128 	/* Now get the IPv4 routing table. */
129 	mib[0] = CTL_NET;
130 	mib[1] = PF_ROUTE;
131 	mib[2] = 0;
132 	mib[3] = AF_INET;
133 	mib[4] = NET_RT_DUMP;
134 	mib[5] = 0;
135 	mib[6] = -1; /* FIB */
136 
137 	for (;;) {
138 		if (sysctl(mib, nitems(mib), NULL, &sz, NULL, 0) != 0)
139 			err(EX_OSERR, "sysctl(NET_RT_DUMP)");
140 		buf = malloc(sz);
141 		error = sysctl(mib, nitems(mib), buf, &sz, NULL, 0);
142 		if (error == 0)
143 			break;
144 		if (errno != ENOMEM)
145 			err(EX_OSERR, "sysctl(NET_RT_DUMP)");
146 		free(buf);
147 	}
148 
149 	ret = NULL;
150 	for (next = buf; next < buf + sz; next += rtm->rtm_msglen) {
151 		rtm = (struct rt_msghdr *)(void *)next;
152 		if (rtm->rtm_version != RTM_VERSION)
153 			continue;
154 		if ((rtm->rtm_flags & RTF_GATEWAY) == 0 ||
155 		    rtm->rtm_index != ifindex)
156 			continue;
157 
158 		dst = gw = mask = NULL;
159 		sa = (struct sockaddr *)(rtm + 1);
160 		for (i = 0; i < RTAX_MAX; i++) {
161 			if ((rtm->rtm_addrs & (1 << i)) != 0) {
162 				switch (i) {
163 				case RTAX_DST:
164 					dst = (void *)sa;
165 					break;
166 				case RTAX_GATEWAY:
167 					gw = (void *)sa;
168 					break;
169 				case RTAX_NETMASK:
170 					mask = (void *)sa;
171 					break;
172 				}
173 			}
174 			sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
175 		}
176 
177 		if (dst->sin_addr.s_addr == INADDR_ANY &&
178 		    mask->sin_addr.s_addr == 0) {
179 			ret = inet_ntoa(gw->sin_addr);
180 			break;
181 		}
182 	}
183 	free(buf);
184 	return (ret);
185 }
186 
187 static void
188 check_size(int fd, const char *fn)
189 {
190 	int name[] = { CTL_HW, HW_PHYSMEM };
191 	size_t namelen = nitems(name);
192 	unsigned long physmem;
193 	size_t len;
194 	off_t mediasize;
195 	int minidump;
196 
197 	len = sizeof(minidump);
198 	if (sysctlbyname("debug.minidump", &minidump, &len, NULL, 0) == 0 &&
199 	    minidump == 1)
200 		return;
201 	len = sizeof(physmem);
202 	if (sysctl(name, namelen, &physmem, &len, NULL, 0) != 0)
203 		err(EX_OSERR, "can't get memory size");
204 	if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) != 0)
205 		err(EX_OSERR, "%s: can't get size", fn);
206 	if ((uintmax_t)mediasize < (uintmax_t)physmem)
207 		errx(EX_IOERR, "%s is smaller than physical memory", fn);
208 }
209 
210 #ifdef HAVE_CRYPTO
211 static void
212 genkey(const char *pubkeyfile, struct diocskerneldump_arg *kdap)
213 {
214 	FILE *fp;
215 	RSA *pubkey;
216 
217 	assert(pubkeyfile != NULL);
218 	assert(kdap != NULL);
219 
220 	fp = NULL;
221 	pubkey = NULL;
222 
223 	fp = fopen(pubkeyfile, "r");
224 	if (fp == NULL)
225 		err(1, "Unable to open %s", pubkeyfile);
226 
227 	if (caph_enter() < 0)
228 		err(1, "Unable to enter capability mode");
229 
230 	pubkey = RSA_new();
231 	if (pubkey == NULL) {
232 		errx(1, "Unable to allocate an RSA structure: %s",
233 		    ERR_error_string(ERR_get_error(), NULL));
234 	}
235 
236 	pubkey = PEM_read_RSA_PUBKEY(fp, &pubkey, NULL, NULL);
237 	fclose(fp);
238 	fp = NULL;
239 	if (pubkey == NULL)
240 		errx(1, "Unable to read data from %s.", pubkeyfile);
241 
242 	/*
243 	 * RSA keys under ~1024 bits are trivially factorable (2018).  OpenSSL
244 	 * provides an API for RSA keys to estimate the symmetric-cipher
245 	 * "equivalent" bits of security (defined in NIST SP800-57), which as
246 	 * of this writing equates a 2048-bit RSA key to 112 symmetric cipher
247 	 * bits.
248 	 *
249 	 * Use this API as a seatbelt to avoid suggesting to users that their
250 	 * privacy is protected by encryption when the key size is insufficient
251 	 * to prevent compromise via factoring.
252 	 *
253 	 * Future work: Sanity check for weak 'e', and sanity check for absence
254 	 * of 'd' (i.e., the supplied key is a public key rather than a full
255 	 * keypair).
256 	 */
257 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
258 	if (RSA_security_bits(pubkey) < 112)
259 #else
260 	if (RSA_size(pubkey) * 8 < 2048)
261 #endif
262 		errx(1, "Small RSA keys (you provided: %db) can be "
263 		    "factored cheaply.  Please generate a larger key.",
264 		    RSA_size(pubkey) * 8);
265 
266 	kdap->kda_encryptedkeysize = RSA_size(pubkey);
267 	if (kdap->kda_encryptedkeysize > KERNELDUMP_ENCKEY_MAX_SIZE) {
268 		errx(1, "Public key has to be at most %db long.",
269 		    8 * KERNELDUMP_ENCKEY_MAX_SIZE);
270 	}
271 
272 	kdap->kda_encryptedkey = calloc(1, kdap->kda_encryptedkeysize);
273 	if (kdap->kda_encryptedkey == NULL)
274 		err(1, "Unable to allocate encrypted key");
275 
276 	/*
277 	 * If no cipher was specified, choose a reasonable default.
278 	 */
279 	if (kdap->kda_encryption == KERNELDUMP_ENC_NONE)
280 		kdap->kda_encryption = KERNELDUMP_ENC_CHACHA20;
281 	else if (kdap->kda_encryption == KERNELDUMP_ENC_AES_256_CBC &&
282 	    kdap->kda_compression != KERNELDUMP_COMP_NONE)
283 		errx(EX_USAGE, "Unpadded AES256-CBC mode cannot be used "
284 		    "with compression.");
285 
286 	arc4random_buf(kdap->kda_key, sizeof(kdap->kda_key));
287 	if (RSA_public_encrypt(sizeof(kdap->kda_key), kdap->kda_key,
288 	    kdap->kda_encryptedkey, pubkey,
289 	    RSA_PKCS1_PADDING) != (int)kdap->kda_encryptedkeysize) {
290 		errx(1, "Unable to encrypt the one-time key.");
291 	}
292 	RSA_free(pubkey);
293 }
294 #endif
295 
296 static void
297 listdumpdev(void)
298 {
299 	static char ip[200];
300 
301 	char dumpdev[PATH_MAX];
302 	struct diocskerneldump_arg ndconf;
303 	size_t len;
304 	const char *sysctlname = "kern.shutdown.dumpdevname";
305 	int fd;
306 
307 	len = sizeof(dumpdev);
308 	if (sysctlbyname(sysctlname, &dumpdev, &len, NULL, 0) != 0) {
309 		if (errno == ENOMEM) {
310 			err(EX_OSERR, "Kernel returned too large of a buffer for '%s'\n",
311 				sysctlname);
312 		} else {
313 			err(EX_OSERR, "Sysctl get '%s'\n", sysctlname);
314 		}
315 	}
316 	if (strlen(dumpdev) == 0)
317 		(void)strlcpy(dumpdev, _PATH_DEVNULL, sizeof(dumpdev));
318 
319 	if (verbose) {
320 		char *ctx, *dd;
321 		unsigned idx;
322 
323 		printf("kernel dumps on priority: device\n");
324 		idx = 0;
325 		ctx = dumpdev;
326 		while ((dd = strsep(&ctx, ",")) != NULL)
327 			printf("%u: %s\n", idx++, dd);
328 	} else
329 		printf("%s\n", dumpdev);
330 
331 	/* If netdump is enabled, print the configuration parameters. */
332 	if (verbose) {
333 		fd = open(_PATH_NETDUMP, O_RDONLY);
334 		if (fd < 0) {
335 			if (errno != ENOENT)
336 				err(EX_OSERR, "opening %s", _PATH_NETDUMP);
337 			return;
338 		}
339 		if (ioctl(fd, DIOCGKERNELDUMP, &ndconf) != 0) {
340 			if (errno != ENXIO)
341 				err(EX_OSERR, "ioctl(DIOCGKERNELDUMP)");
342 			(void)close(fd);
343 			return;
344 		}
345 
346 		printf("server address: %s\n",
347 		    inet_ntop(ndconf.kda_af, &ndconf.kda_server, ip,
348 			sizeof(ip)));
349 		printf("client address: %s\n",
350 		    inet_ntop(ndconf.kda_af, &ndconf.kda_client, ip,
351 			sizeof(ip)));
352 		printf("gateway address: %s\n",
353 		    inet_ntop(ndconf.kda_af, &ndconf.kda_gateway, ip,
354 			sizeof(ip)));
355 		(void)close(fd);
356 	}
357 }
358 
359 static int
360 opendumpdev(const char *arg, char *dumpdev)
361 {
362 	int fd, i;
363 
364 	if (strncmp(arg, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
365 		strlcpy(dumpdev, arg, PATH_MAX);
366 	else {
367 		i = snprintf(dumpdev, PATH_MAX, "%s%s", _PATH_DEV, arg);
368 		if (i < 0)
369 			err(EX_OSERR, "%s", arg);
370 		if (i >= PATH_MAX)
371 			errc(EX_DATAERR, EINVAL, "%s", arg);
372 	}
373 
374 	fd = open(dumpdev, O_RDONLY);
375 	if (fd < 0)
376 		err(EX_OSFILE, "%s", dumpdev);
377 	return (fd);
378 }
379 
380 int
381 main(int argc, char *argv[])
382 {
383 	char dumpdev[PATH_MAX];
384 	struct diocskerneldump_arg ndconf, *kdap;
385 	struct addrinfo hints, *res;
386 	const char *dev, *pubkeyfile, *server, *client, *gateway;
387 	int ch, error, fd, cipher;
388 	bool gzip, list, netdump, zstd, insert, rflag;
389 	uint8_t ins_idx;
390 
391 	gzip = list = netdump = zstd = insert = rflag = false;
392 	kdap = NULL;
393 	pubkeyfile = NULL;
394 	server = client = gateway = NULL;
395 	ins_idx = KDA_APPEND;
396 	cipher = KERNELDUMP_ENC_NONE;
397 
398 	while ((ch = getopt(argc, argv, "C:c:g:i:k:lrs:vZz")) != -1)
399 		switch ((char)ch) {
400 		case 'C':
401 			if (strcasecmp(optarg, "chacha") == 0 ||
402 			    strcasecmp(optarg, "chacha20") == 0)
403 				cipher = KERNELDUMP_ENC_CHACHA20;
404 			else if (strcasecmp(optarg, "aes-cbc") == 0 ||
405 			    strcasecmp(optarg, "aes256-cbc") == 0)
406 				cipher = KERNELDUMP_ENC_AES_256_CBC;
407 			else
408 				errx(EX_USAGE, "Unrecognized cipher algorithm "
409 				    "'%s'", optarg);
410 			break;
411 		case 'c':
412 			client = optarg;
413 			break;
414 		case 'g':
415 			gateway = optarg;
416 			break;
417 		case 'i':
418 			{
419 			int i;
420 
421 			i = atoi(optarg);
422 			if (i < 0 || i >= KDA_APPEND - 1)
423 				errx(EX_USAGE,
424 				    "-i index must be between zero and %d.",
425 				    (int)KDA_APPEND - 2);
426 			insert = true;
427 			ins_idx = i;
428 			}
429 			break;
430 		case 'k':
431 			pubkeyfile = optarg;
432 			break;
433 		case 'l':
434 			list = true;
435 			break;
436 		case 'r':
437 			rflag = true;
438 			break;
439 		case 's':
440 			server = optarg;
441 			break;
442 		case 'v':
443 			verbose = 1;
444 			break;
445 		case 'Z':
446 			zstd = true;
447 			break;
448 		case 'z':
449 			gzip = true;
450 			break;
451 		default:
452 			usage();
453 		}
454 
455 	if (gzip && zstd)
456 		errx(EX_USAGE, "The -z and -Z options are mutually exclusive.");
457 
458 	if (insert && rflag)
459 		errx(EX_USAGE, "The -i and -r options are mutually exclusive.");
460 
461 	argc -= optind;
462 	argv += optind;
463 
464 	if (list) {
465 		listdumpdev();
466 		exit(EX_OK);
467 	}
468 
469 	if (argc != 1)
470 		usage();
471 
472 #ifdef HAVE_CRYPTO
473 	if (cipher != KERNELDUMP_ENC_NONE && pubkeyfile == NULL)
474 		errx(EX_USAGE, "-C option requires a public key file.");
475 #else
476 	if (pubkeyfile != NULL)
477 		errx(EX_UNAVAILABLE,"Unable to use the public key."
478 				    " Recompile dumpon with OpenSSL support.");
479 #endif
480 
481 	if (server != NULL && client != NULL) {
482 		dev = _PATH_NETDUMP;
483 		netdump = true;
484 	} else if (server == NULL && client == NULL && argc > 0) {
485 		if (strcmp(argv[0], "off") == 0) {
486 			rflag = true;
487 			dev = _PATH_DEVNULL;
488 		} else
489 			dev = argv[0];
490 		netdump = false;
491 	} else
492 		usage();
493 
494 	fd = opendumpdev(dev, dumpdev);
495 	if (!netdump && !gzip && !zstd && !rflag)
496 		check_size(fd, dumpdev);
497 
498 	kdap = &ndconf;
499 	bzero(kdap, sizeof(*kdap));
500 
501 	if (rflag)
502 		kdap->kda_index = KDA_REMOVE;
503 	else
504 		kdap->kda_index = ins_idx;
505 
506 	kdap->kda_compression = KERNELDUMP_COMP_NONE;
507 	if (zstd)
508 		kdap->kda_compression = KERNELDUMP_COMP_ZSTD;
509 	else if (gzip)
510 		kdap->kda_compression = KERNELDUMP_COMP_GZIP;
511 
512 	if (netdump) {
513 		memset(&hints, 0, sizeof(hints));
514 		hints.ai_family = AF_INET;
515 		hints.ai_protocol = IPPROTO_UDP;
516 		res = NULL;
517 		error = getaddrinfo(server, NULL, &hints, &res);
518 		if (error != 0)
519 			err(1, "%s", gai_strerror(error));
520 		if (res == NULL)
521 			errx(1, "failed to resolve '%s'", server);
522 		server = inet_ntoa(
523 		    ((struct sockaddr_in *)(void *)res->ai_addr)->sin_addr);
524 		freeaddrinfo(res);
525 
526 		if (strlcpy(ndconf.kda_iface, argv[0],
527 		    sizeof(ndconf.kda_iface)) >= sizeof(ndconf.kda_iface))
528 			errx(EX_USAGE, "invalid interface name '%s'", argv[0]);
529 		if (inet_aton(server, &ndconf.kda_server.in4) == 0)
530 			errx(EX_USAGE, "invalid server address '%s'", server);
531 		if (inet_aton(client, &ndconf.kda_client.in4) == 0)
532 			errx(EX_USAGE, "invalid client address '%s'", client);
533 
534 		if (gateway == NULL) {
535 			gateway = find_gateway(argv[0]);
536 			if (gateway == NULL) {
537 				if (verbose)
538 					printf(
539 				    "failed to look up gateway for %s\n",
540 					    server);
541 				gateway = server;
542 			}
543 		}
544 		if (inet_aton(gateway, &ndconf.kda_gateway.in4) == 0)
545 			errx(EX_USAGE, "invalid gateway address '%s'", gateway);
546 		ndconf.kda_af = AF_INET;
547 	}
548 
549 #ifdef HAVE_CRYPTO
550 	if (pubkeyfile != NULL) {
551 		kdap->kda_encryption = cipher;
552 		genkey(pubkeyfile, kdap);
553 	}
554 #endif
555 	error = ioctl(fd, DIOCSKERNELDUMP, kdap);
556 	if (error != 0)
557 		error = errno;
558 	explicit_bzero(kdap->kda_encryptedkey, kdap->kda_encryptedkeysize);
559 	free(kdap->kda_encryptedkey);
560 	explicit_bzero(kdap, sizeof(*kdap));
561 	if (error != 0) {
562 		if (netdump) {
563 			/*
564 			 * Be slightly less user-hostile for some common
565 			 * errors, especially as users don't have any great
566 			 * discoverability into which NICs support netdump.
567 			 */
568 			if (error == ENXIO)
569 				errx(EX_OSERR, "Unable to configure netdump "
570 				    "because the interface's link is down.");
571 			else if (error == ENODEV)
572 				errx(EX_OSERR, "Unable to configure netdump "
573 				    "because the interface driver does not yet "
574 				    "support netdump.");
575 		}
576 		errc(EX_OSERR, error, "ioctl(DIOCSKERNELDUMP)");
577 	}
578 
579 	if (verbose)
580 		listdumpdev();
581 
582 	exit(EX_OK);
583 }
584