]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/dumpon/dumpon.c
Remove spurious newline
[FreeBSD/FreeBSD.git] / sbin / dumpon / dumpon.c
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                 if (verbose)
208                         printf("%s is smaller than physical memory\n", fn);
209                 exit(EX_IOERR);
210         }
211 }
212
213 #ifdef HAVE_CRYPTO
214 static void
215 genkey(const char *pubkeyfile, struct diocskerneldump_arg *kdap)
216 {
217         FILE *fp;
218         RSA *pubkey;
219
220         assert(pubkeyfile != NULL);
221         assert(kdap != NULL);
222
223         fp = NULL;
224         pubkey = NULL;
225
226         fp = fopen(pubkeyfile, "r");
227         if (fp == NULL)
228                 err(1, "Unable to open %s", pubkeyfile);
229
230         if (caph_enter() < 0)
231                 err(1, "Unable to enter capability mode");
232
233         pubkey = RSA_new();
234         if (pubkey == NULL) {
235                 errx(1, "Unable to allocate an RSA structure: %s",
236                     ERR_error_string(ERR_get_error(), NULL));
237         }
238
239         pubkey = PEM_read_RSA_PUBKEY(fp, &pubkey, NULL, NULL);
240         fclose(fp);
241         fp = NULL;
242         if (pubkey == NULL)
243                 errx(1, "Unable to read data from %s.", pubkeyfile);
244
245         /*
246          * RSA keys under ~1024 bits are trivially factorable (2018).  OpenSSL
247          * provides an API for RSA keys to estimate the symmetric-cipher
248          * "equivalent" bits of security (defined in NIST SP800-57), which as
249          * of this writing equates a 2048-bit RSA key to 112 symmetric cipher
250          * bits.
251          *
252          * Use this API as a seatbelt to avoid suggesting to users that their
253          * privacy is protected by encryption when the key size is insufficient
254          * to prevent compromise via factoring.
255          *
256          * Future work: Sanity check for weak 'e', and sanity check for absence
257          * of 'd' (i.e., the supplied key is a public key rather than a full
258          * keypair).
259          */
260 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
261         if (RSA_security_bits(pubkey) < 112)
262 #else
263         if (RSA_size(pubkey) * 8 < 2048)
264 #endif
265                 errx(1, "Small RSA keys (you provided: %db) can be "
266                     "factored cheaply.  Please generate a larger key.",
267                     RSA_size(pubkey) * 8);
268
269         kdap->kda_encryptedkeysize = RSA_size(pubkey);
270         if (kdap->kda_encryptedkeysize > KERNELDUMP_ENCKEY_MAX_SIZE) {
271                 errx(1, "Public key has to be at most %db long.",
272                     8 * KERNELDUMP_ENCKEY_MAX_SIZE);
273         }
274
275         kdap->kda_encryptedkey = calloc(1, kdap->kda_encryptedkeysize);
276         if (kdap->kda_encryptedkey == NULL)
277                 err(1, "Unable to allocate encrypted key");
278
279         kdap->kda_encryption = KERNELDUMP_ENC_AES_256_CBC;
280         arc4random_buf(kdap->kda_key, sizeof(kdap->kda_key));
281         if (RSA_public_encrypt(sizeof(kdap->kda_key), kdap->kda_key,
282             kdap->kda_encryptedkey, pubkey,
283             RSA_PKCS1_PADDING) != (int)kdap->kda_encryptedkeysize) {
284                 errx(1, "Unable to encrypt the one-time key.");
285         }
286         RSA_free(pubkey);
287 }
288 #endif
289
290 static void
291 listdumpdev(void)
292 {
293         static char ip[200];
294
295         char dumpdev[PATH_MAX];
296         struct diocskerneldump_arg ndconf;
297         size_t len;
298         const char *sysctlname = "kern.shutdown.dumpdevname";
299         int fd;
300
301         len = sizeof(dumpdev);
302         if (sysctlbyname(sysctlname, &dumpdev, &len, NULL, 0) != 0) {
303                 if (errno == ENOMEM) {
304                         err(EX_OSERR, "Kernel returned too large of a buffer for '%s'\n",
305                                 sysctlname);
306                 } else {
307                         err(EX_OSERR, "Sysctl get '%s'\n", sysctlname);
308                 }
309         }
310         if (strlen(dumpdev) == 0)
311                 (void)strlcpy(dumpdev, _PATH_DEVNULL, sizeof(dumpdev));
312
313         if (verbose) {
314                 char *ctx, *dd;
315                 unsigned idx;
316
317                 printf("kernel dumps on priority: device\n");
318                 idx = 0;
319                 ctx = dumpdev;
320                 while ((dd = strsep(&ctx, ",")) != NULL)
321                         printf("%u: %s\n", idx++, dd);
322         } else
323                 printf("%s\n", dumpdev);
324
325         /* If netdump is enabled, print the configuration parameters. */
326         if (verbose) {
327                 fd = open(_PATH_NETDUMP, O_RDONLY);
328                 if (fd < 0) {
329                         if (errno != ENOENT)
330                                 err(EX_OSERR, "opening %s", _PATH_NETDUMP);
331                         return;
332                 }
333                 if (ioctl(fd, DIOCGKERNELDUMP, &ndconf) != 0) {
334                         if (errno != ENXIO)
335                                 err(EX_OSERR, "ioctl(DIOCGKERNELDUMP)");
336                         (void)close(fd);
337                         return;
338                 }
339
340                 printf("server address: %s\n",
341                     inet_ntop(ndconf.kda_af, &ndconf.kda_server, ip,
342                         sizeof(ip)));
343                 printf("client address: %s\n",
344                     inet_ntop(ndconf.kda_af, &ndconf.kda_client, ip,
345                         sizeof(ip)));
346                 printf("gateway address: %s\n",
347                     inet_ntop(ndconf.kda_af, &ndconf.kda_gateway, ip,
348                         sizeof(ip)));
349                 (void)close(fd);
350         }
351 }
352
353 static int
354 opendumpdev(const char *arg, char *dumpdev)
355 {
356         int fd, i;
357
358         if (strncmp(arg, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
359                 strlcpy(dumpdev, arg, PATH_MAX);
360         else {
361                 i = snprintf(dumpdev, PATH_MAX, "%s%s", _PATH_DEV, arg);
362                 if (i < 0)
363                         err(EX_OSERR, "%s", arg);
364                 if (i >= PATH_MAX)
365                         errc(EX_DATAERR, EINVAL, "%s", arg);
366         }
367
368         fd = open(dumpdev, O_RDONLY);
369         if (fd < 0)
370                 err(EX_OSFILE, "%s", dumpdev);
371         return (fd);
372 }
373
374 int
375 main(int argc, char *argv[])
376 {
377         char dumpdev[PATH_MAX];
378         struct diocskerneldump_arg ndconf, *kdap;
379         struct addrinfo hints, *res;
380         const char *dev, *pubkeyfile, *server, *client, *gateway;
381         int ch, error, fd;
382         bool gzip, list, netdump, zstd, insert, rflag;
383         uint8_t ins_idx;
384
385         gzip = list = netdump = zstd = insert = rflag = false;
386         kdap = NULL;
387         pubkeyfile = NULL;
388         server = client = gateway = NULL;
389         ins_idx = KDA_APPEND;
390
391         while ((ch = getopt(argc, argv, "c:g:i:k:lrs:vZz")) != -1)
392                 switch ((char)ch) {
393                 case 'c':
394                         client = optarg;
395                         break;
396                 case 'g':
397                         gateway = optarg;
398                         break;
399                 case 'i':
400                         {
401                         int i;
402
403                         i = atoi(optarg);
404                         if (i < 0 || i >= KDA_APPEND - 1)
405                                 errx(EX_USAGE,
406                                     "-i index must be between zero and %d.",
407                                     (int)KDA_APPEND - 2);
408                         insert = true;
409                         ins_idx = i;
410                         }
411                         break;
412                 case 'k':
413                         pubkeyfile = optarg;
414                         break;
415                 case 'l':
416                         list = true;
417                         break;
418                 case 'r':
419                         rflag = true;
420                         break;
421                 case 's':
422                         server = optarg;
423                         break;
424                 case 'v':
425                         verbose = 1;
426                         break;
427                 case 'Z':
428                         zstd = true;
429                         break;
430                 case 'z':
431                         gzip = true;
432                         break;
433                 default:
434                         usage();
435                 }
436
437         if (gzip && zstd)
438                 errx(EX_USAGE, "The -z and -Z options are mutually exclusive.");
439
440         if (insert && rflag)
441                 errx(EX_USAGE, "The -i and -r options are mutually exclusive.");
442
443         argc -= optind;
444         argv += optind;
445
446         if (list) {
447                 listdumpdev();
448                 exit(EX_OK);
449         }
450
451         if (argc != 1)
452                 usage();
453
454 #ifndef HAVE_CRYPTO
455         if (pubkeyfile != NULL)
456                 errx(EX_UNAVAILABLE,"Unable to use the public key."
457                                     " Recompile dumpon with OpenSSL support.");
458 #endif
459
460         if (server != NULL && client != NULL) {
461                 dev = _PATH_NETDUMP;
462                 netdump = true;
463         } else if (server == NULL && client == NULL && argc > 0) {
464                 if (strcmp(argv[0], "off") == 0) {
465                         rflag = true;
466                         dev = _PATH_DEVNULL;
467                 } else
468                         dev = argv[0];
469                 netdump = false;
470         } else
471                 usage();
472
473         fd = opendumpdev(dev, dumpdev);
474         if (!netdump && !gzip && !rflag)
475                 check_size(fd, dumpdev);
476
477         kdap = &ndconf;
478         bzero(kdap, sizeof(*kdap));
479
480         if (rflag)
481                 kdap->kda_index = KDA_REMOVE;
482         else
483                 kdap->kda_index = ins_idx;
484
485         kdap->kda_compression = KERNELDUMP_COMP_NONE;
486         if (zstd)
487                 kdap->kda_compression = KERNELDUMP_COMP_ZSTD;
488         else if (gzip)
489                 kdap->kda_compression = KERNELDUMP_COMP_GZIP;
490
491         if (netdump) {
492                 memset(&hints, 0, sizeof(hints));
493                 hints.ai_family = AF_INET;
494                 hints.ai_protocol = IPPROTO_UDP;
495                 res = NULL;
496                 error = getaddrinfo(server, NULL, &hints, &res);
497                 if (error != 0)
498                         err(1, "%s", gai_strerror(error));
499                 if (res == NULL)
500                         errx(1, "failed to resolve '%s'", server);
501                 server = inet_ntoa(
502                     ((struct sockaddr_in *)(void *)res->ai_addr)->sin_addr);
503                 freeaddrinfo(res);
504
505                 if (strlcpy(ndconf.kda_iface, argv[0],
506                     sizeof(ndconf.kda_iface)) >= sizeof(ndconf.kda_iface))
507                         errx(EX_USAGE, "invalid interface name '%s'", argv[0]);
508                 if (inet_aton(server, &ndconf.kda_server.in4) == 0)
509                         errx(EX_USAGE, "invalid server address '%s'", server);
510                 if (inet_aton(client, &ndconf.kda_client.in4) == 0)
511                         errx(EX_USAGE, "invalid client address '%s'", client);
512
513                 if (gateway == NULL) {
514                         gateway = find_gateway(argv[0]);
515                         if (gateway == NULL) {
516                                 if (verbose)
517                                         printf(
518                                     "failed to look up gateway for %s\n",
519                                             server);
520                                 gateway = server;
521                         }
522                 }
523                 if (inet_aton(gateway, &ndconf.kda_gateway.in4) == 0)
524                         errx(EX_USAGE, "invalid gateway address '%s'", gateway);
525                 ndconf.kda_af = AF_INET;
526         }
527
528 #ifdef HAVE_CRYPTO
529         if (pubkeyfile != NULL)
530                 genkey(pubkeyfile, kdap);
531 #endif
532         error = ioctl(fd, DIOCSKERNELDUMP, kdap);
533         if (error != 0)
534                 error = errno;
535         explicit_bzero(kdap->kda_encryptedkey, kdap->kda_encryptedkeysize);
536         free(kdap->kda_encryptedkey);
537         explicit_bzero(kdap, sizeof(*kdap));
538         if (error != 0) {
539                 if (netdump) {
540                         /*
541                          * Be slightly less user-hostile for some common
542                          * errors, especially as users don't have any great
543                          * discoverability into which NICs support netdump.
544                          */
545                         if (error == ENXIO)
546                                 errx(EX_OSERR, "Unable to configure netdump "
547                                     "because the interface's link is down.");
548                         else if (error == ENODEV)
549                                 errx(EX_OSERR, "Unable to configure netdump "
550                                     "because the interface driver does not yet "
551                                     "support netdump.");
552                 }
553                 errc(EX_OSERR, error, "ioctl(DIOCSKERNELDUMP)");
554         }
555
556         if (verbose)
557                 listdumpdev();
558
559         exit(EX_OK);
560 }