]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/dumpon/dumpon.c
tests: add more netlink tests for neighbors/routes
[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/rand.h>
81 #include <openssl/rsa.h>
82 #endif
83
84 static int      verbose;
85
86 static void _Noreturn
87 usage(void)
88 {
89         fprintf(stderr,
90     "usage: dumpon [-i index] [-r] [-v] [-k <pubkey>] [-Zz] <device>\n"
91     "       dumpon [-i index] [-r] [-v] [-k <pubkey>] [-Zz]\n"
92     "              [-g <gateway>] -s <server> -c <client> <iface>\n"
93     "       dumpon [-v] off\n"
94     "       dumpon [-v] -l\n");
95         exit(EX_USAGE);
96 }
97
98 /*
99  * Look for a default route on the specified interface.
100  */
101 static char *
102 find_gateway(const char *ifname)
103 {
104         struct ifaddrs *ifa, *ifap;
105         struct rt_msghdr *rtm;
106         struct sockaddr *sa;
107         struct sockaddr_dl *sdl;
108         struct sockaddr_in *dst, *mask, *gw;
109         char *buf, *next, *ret;
110         size_t sz;
111         int error, i, ifindex, mib[7];
112
113         /* First look up the interface index. */
114         if (getifaddrs(&ifap) != 0)
115                 err(EX_OSERR, "getifaddrs");
116         for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
117                 if (ifa->ifa_addr->sa_family != AF_LINK)
118                         continue;
119                 if (strcmp(ifa->ifa_name, ifname) == 0) {
120                         sdl = (struct sockaddr_dl *)(void *)ifa->ifa_addr;
121                         ifindex = sdl->sdl_index;
122                         break;
123                 }
124         }
125         if (ifa == NULL)
126                 errx(1, "couldn't find interface index for '%s'", ifname);
127         freeifaddrs(ifap);
128
129         /* Now get the IPv4 routing table. */
130         mib[0] = CTL_NET;
131         mib[1] = PF_ROUTE;
132         mib[2] = 0;
133         mib[3] = AF_INET;
134         mib[4] = NET_RT_DUMP;
135         mib[5] = 0;
136         mib[6] = -1; /* FIB */
137
138         for (;;) {
139                 if (sysctl(mib, nitems(mib), NULL, &sz, NULL, 0) != 0)
140                         err(EX_OSERR, "sysctl(NET_RT_DUMP)");
141                 buf = malloc(sz);
142                 error = sysctl(mib, nitems(mib), buf, &sz, NULL, 0);
143                 if (error == 0)
144                         break;
145                 if (errno != ENOMEM)
146                         err(EX_OSERR, "sysctl(NET_RT_DUMP)");
147                 free(buf);
148         }
149
150         ret = NULL;
151         for (next = buf; next < buf + sz; next += rtm->rtm_msglen) {
152                 rtm = (struct rt_msghdr *)(void *)next;
153                 if (rtm->rtm_version != RTM_VERSION)
154                         continue;
155                 if ((rtm->rtm_flags & RTF_GATEWAY) == 0 ||
156                     rtm->rtm_index != ifindex)
157                         continue;
158
159                 dst = gw = mask = NULL;
160                 sa = (struct sockaddr *)(rtm + 1);
161                 for (i = 0; i < RTAX_MAX; i++) {
162                         if ((rtm->rtm_addrs & (1 << i)) != 0) {
163                                 switch (i) {
164                                 case RTAX_DST:
165                                         dst = (void *)sa;
166                                         break;
167                                 case RTAX_GATEWAY:
168                                         gw = (void *)sa;
169                                         break;
170                                 case RTAX_NETMASK:
171                                         mask = (void *)sa;
172                                         break;
173                                 }
174                         }
175                         sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
176                 }
177
178                 if (dst->sin_addr.s_addr == INADDR_ANY &&
179                     mask->sin_addr.s_addr == 0) {
180                         ret = inet_ntoa(gw->sin_addr);
181                         break;
182                 }
183         }
184         free(buf);
185         return (ret);
186 }
187
188 static void
189 check_link_status(const char *ifname)
190 {
191         struct ifaddrs *ifap, *ifa;
192
193         if (getifaddrs(&ifap) != 0)
194                 err(EX_OSERR, "getifaddrs");
195
196         for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
197                 if (strcmp(ifname, ifa->ifa_name) != 0)
198                         continue;
199                 if ((ifa->ifa_flags & IFF_UP) == 0) {
200                         warnx("warning: %s's link is down", ifname);
201                 }
202                 break;
203         }
204         freeifaddrs(ifap);
205 }
206
207 static void
208 check_size(int fd, const char *fn)
209 {
210         int name[] = { CTL_HW, HW_PHYSMEM };
211         size_t namelen = nitems(name);
212         unsigned long physmem;
213         size_t len;
214         off_t mediasize;
215         int minidump;
216
217         len = sizeof(minidump);
218         if (sysctlbyname("debug.minidump", &minidump, &len, NULL, 0) == 0 &&
219             minidump == 1)
220                 return;
221         len = sizeof(physmem);
222         if (sysctl(name, namelen, &physmem, &len, NULL, 0) != 0)
223                 err(EX_OSERR, "can't get memory size");
224         if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) != 0)
225                 err(EX_OSERR, "%s: can't get size", fn);
226         if ((uintmax_t)mediasize < (uintmax_t)physmem)
227                 errx(EX_IOERR, "%s is smaller than physical memory", fn);
228 }
229
230 #ifdef HAVE_CRYPTO
231 static void
232 genkey(const char *pubkeyfile, struct diocskerneldump_arg *kdap)
233 {
234         FILE *fp;
235         RSA *pubkey;
236
237         assert(pubkeyfile != NULL);
238         assert(kdap != NULL);
239
240         fp = NULL;
241         pubkey = NULL;
242
243         fp = fopen(pubkeyfile, "r");
244         if (fp == NULL)
245                 err(1, "Unable to open %s", pubkeyfile);
246
247         /*
248          * Obsolescent OpenSSL only knows about /dev/random, and needs to
249          * pre-seed before entering cap mode.  For whatever reason,
250          * RSA_pub_encrypt uses the internal PRNG.
251          */
252 #if OPENSSL_VERSION_NUMBER < 0x10100000L
253         {
254                 unsigned char c[1];
255                 RAND_bytes(c, 1);
256         }
257 #endif
258
259         if (caph_enter() < 0)
260                 err(1, "Unable to enter capability mode");
261
262         pubkey = RSA_new();
263         if (pubkey == NULL) {
264                 errx(1, "Unable to allocate an RSA structure: %s",
265                     ERR_error_string(ERR_get_error(), NULL));
266         }
267
268         pubkey = PEM_read_RSA_PUBKEY(fp, &pubkey, NULL, NULL);
269         fclose(fp);
270         fp = NULL;
271         if (pubkey == NULL)
272                 errx(1, "Unable to read data from %s.", pubkeyfile);
273
274         /*
275          * RSA keys under ~1024 bits are trivially factorable (2018).  OpenSSL
276          * provides an API for RSA keys to estimate the symmetric-cipher
277          * "equivalent" bits of security (defined in NIST SP800-57), which as
278          * of this writing equates a 2048-bit RSA key to 112 symmetric cipher
279          * bits.
280          *
281          * Use this API as a seatbelt to avoid suggesting to users that their
282          * privacy is protected by encryption when the key size is insufficient
283          * to prevent compromise via factoring.
284          *
285          * Future work: Sanity check for weak 'e', and sanity check for absence
286          * of 'd' (i.e., the supplied key is a public key rather than a full
287          * keypair).
288          */
289 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
290         if (RSA_security_bits(pubkey) < 112)
291 #else
292         if (RSA_size(pubkey) * 8 < 2048)
293 #endif
294                 errx(1, "Small RSA keys (you provided: %db) can be "
295                     "factored cheaply.  Please generate a larger key.",
296                     RSA_size(pubkey) * 8);
297
298         kdap->kda_encryptedkeysize = RSA_size(pubkey);
299         if (kdap->kda_encryptedkeysize > KERNELDUMP_ENCKEY_MAX_SIZE) {
300                 errx(1, "Public key has to be at most %db long.",
301                     8 * KERNELDUMP_ENCKEY_MAX_SIZE);
302         }
303
304         kdap->kda_encryptedkey = calloc(1, kdap->kda_encryptedkeysize);
305         if (kdap->kda_encryptedkey == NULL)
306                 err(1, "Unable to allocate encrypted key");
307
308         /*
309          * If no cipher was specified, choose a reasonable default.
310          */
311         if (kdap->kda_encryption == KERNELDUMP_ENC_NONE)
312                 kdap->kda_encryption = KERNELDUMP_ENC_CHACHA20;
313         else if (kdap->kda_encryption == KERNELDUMP_ENC_AES_256_CBC &&
314             kdap->kda_compression != KERNELDUMP_COMP_NONE)
315                 errx(EX_USAGE, "Unpadded AES256-CBC mode cannot be used "
316                     "with compression.");
317
318         arc4random_buf(kdap->kda_key, sizeof(kdap->kda_key));
319         if (RSA_public_encrypt(sizeof(kdap->kda_key), kdap->kda_key,
320             kdap->kda_encryptedkey, pubkey,
321             RSA_PKCS1_OAEP_PADDING) != (int)kdap->kda_encryptedkeysize) {
322                 errx(1, "Unable to encrypt the one-time key: %s",
323                     ERR_error_string(ERR_get_error(), NULL));
324         }
325         RSA_free(pubkey);
326 }
327 #endif
328
329 static void
330 listdumpdev(void)
331 {
332         static char ip[200];
333
334         char dumpdev[PATH_MAX];
335         struct diocskerneldump_arg ndconf;
336         size_t len;
337         const char *sysctlname = "kern.shutdown.dumpdevname";
338         int fd;
339
340         len = sizeof(dumpdev);
341         if (sysctlbyname(sysctlname, &dumpdev, &len, NULL, 0) != 0) {
342                 if (errno == ENOMEM) {
343                         err(EX_OSERR, "Kernel returned too large of a buffer for '%s'\n",
344                                 sysctlname);
345                 } else {
346                         err(EX_OSERR, "Sysctl get '%s'\n", sysctlname);
347                 }
348         }
349         if (strlen(dumpdev) == 0)
350                 (void)strlcpy(dumpdev, _PATH_DEVNULL, sizeof(dumpdev));
351
352         if (verbose) {
353                 char *ctx, *dd;
354                 unsigned idx;
355
356                 printf("kernel dumps on priority: device\n");
357                 idx = 0;
358                 ctx = dumpdev;
359                 while ((dd = strsep(&ctx, ",")) != NULL)
360                         printf("%u: %s\n", idx++, dd);
361         } else
362                 printf("%s\n", dumpdev);
363
364         /* If netdump is enabled, print the configuration parameters. */
365         if (verbose) {
366                 fd = open(_PATH_NETDUMP, O_RDONLY);
367                 if (fd < 0) {
368                         if (errno != ENOENT)
369                                 err(EX_OSERR, "opening %s", _PATH_NETDUMP);
370                         return;
371                 }
372                 if (ioctl(fd, DIOCGKERNELDUMP, &ndconf) != 0) {
373                         if (errno != ENXIO)
374                                 err(EX_OSERR, "ioctl(DIOCGKERNELDUMP)");
375                         (void)close(fd);
376                         return;
377                 }
378
379                 printf("server address: %s\n",
380                     inet_ntop(ndconf.kda_af, &ndconf.kda_server, ip,
381                         sizeof(ip)));
382                 printf("client address: %s\n",
383                     inet_ntop(ndconf.kda_af, &ndconf.kda_client, ip,
384                         sizeof(ip)));
385                 printf("gateway address: %s\n",
386                     inet_ntop(ndconf.kda_af, &ndconf.kda_gateway, ip,
387                         sizeof(ip)));
388                 (void)close(fd);
389         }
390 }
391
392 static int
393 opendumpdev(const char *arg, char *dumpdev)
394 {
395         int fd, i;
396
397         if (strncmp(arg, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
398                 strlcpy(dumpdev, arg, PATH_MAX);
399         else {
400                 i = snprintf(dumpdev, PATH_MAX, "%s%s", _PATH_DEV, arg);
401                 if (i < 0)
402                         err(EX_OSERR, "%s", arg);
403                 if (i >= PATH_MAX)
404                         errc(EX_DATAERR, EINVAL, "%s", arg);
405         }
406
407         fd = open(dumpdev, O_RDONLY);
408         if (fd < 0)
409                 err(EX_OSFILE, "%s", dumpdev);
410         return (fd);
411 }
412
413 int
414 main(int argc, char *argv[])
415 {
416         char dumpdev[PATH_MAX];
417         struct diocskerneldump_arg ndconf, *kdap;
418         struct addrinfo hints, *res;
419         const char *dev, *pubkeyfile, *server, *client, *gateway;
420         int ch, error, fd, cipher;
421         bool gzip, list, netdump, zstd, insert, rflag;
422         uint8_t ins_idx;
423
424         gzip = list = netdump = zstd = insert = rflag = false;
425         kdap = NULL;
426         pubkeyfile = NULL;
427         server = client = gateway = NULL;
428         ins_idx = KDA_APPEND;
429         cipher = KERNELDUMP_ENC_NONE;
430
431         while ((ch = getopt(argc, argv, "C:c:g:i:k:lrs:vZz")) != -1)
432                 switch ((char)ch) {
433                 case 'C':
434                         if (strcasecmp(optarg, "chacha") == 0 ||
435                             strcasecmp(optarg, "chacha20") == 0)
436                                 cipher = KERNELDUMP_ENC_CHACHA20;
437                         else if (strcasecmp(optarg, "aes-cbc") == 0 ||
438                             strcasecmp(optarg, "aes256-cbc") == 0)
439                                 cipher = KERNELDUMP_ENC_AES_256_CBC;
440                         else
441                                 errx(EX_USAGE, "Unrecognized cipher algorithm "
442                                     "'%s'", optarg);
443                         break;
444                 case 'c':
445                         client = optarg;
446                         break;
447                 case 'g':
448                         gateway = optarg;
449                         break;
450                 case 'i':
451                         {
452                         int i;
453
454                         i = atoi(optarg);
455                         if (i < 0 || i >= KDA_APPEND - 1)
456                                 errx(EX_USAGE,
457                                     "-i index must be between zero and %d.",
458                                     (int)KDA_APPEND - 2);
459                         insert = true;
460                         ins_idx = i;
461                         }
462                         break;
463                 case 'k':
464                         pubkeyfile = optarg;
465                         break;
466                 case 'l':
467                         list = true;
468                         break;
469                 case 'r':
470                         rflag = true;
471                         break;
472                 case 's':
473                         server = optarg;
474                         break;
475                 case 'v':
476                         verbose = 1;
477                         break;
478                 case 'Z':
479                         zstd = true;
480                         break;
481                 case 'z':
482                         gzip = true;
483                         break;
484                 default:
485                         usage();
486                 }
487
488         if (gzip && zstd)
489                 errx(EX_USAGE, "The -z and -Z options are mutually exclusive.");
490
491         if (insert && rflag)
492                 errx(EX_USAGE, "The -i and -r options are mutually exclusive.");
493
494         argc -= optind;
495         argv += optind;
496
497         if (list) {
498                 listdumpdev();
499                 exit(EX_OK);
500         }
501
502         if (argc != 1)
503                 usage();
504
505 #ifdef HAVE_CRYPTO
506         if (cipher != KERNELDUMP_ENC_NONE && pubkeyfile == NULL) {
507                 errx(EX_USAGE, "-C option requires a public key file.");
508         } else if (pubkeyfile != NULL) {
509                 ERR_load_crypto_strings();
510         }
511 #else
512         if (pubkeyfile != NULL)
513                 errx(EX_UNAVAILABLE,"Unable to use the public key."
514                                     " Recompile dumpon with OpenSSL support.");
515 #endif
516
517         if (server != NULL && client != NULL) {
518                 dev = _PATH_NETDUMP;
519                 netdump = true;
520         } else if (server == NULL && client == NULL && argc > 0) {
521                 if (strcmp(argv[0], "off") == 0) {
522                         rflag = true;
523                         dev = _PATH_DEVNULL;
524                 } else
525                         dev = argv[0];
526                 netdump = false;
527         } else
528                 usage();
529
530         fd = opendumpdev(dev, dumpdev);
531         if (!netdump && !gzip && !zstd && !rflag)
532                 check_size(fd, dumpdev);
533
534         kdap = &ndconf;
535         bzero(kdap, sizeof(*kdap));
536
537         if (rflag)
538                 kdap->kda_index = KDA_REMOVE;
539         else
540                 kdap->kda_index = ins_idx;
541
542         kdap->kda_compression = KERNELDUMP_COMP_NONE;
543         if (zstd)
544                 kdap->kda_compression = KERNELDUMP_COMP_ZSTD;
545         else if (gzip)
546                 kdap->kda_compression = KERNELDUMP_COMP_GZIP;
547
548         if (netdump) {
549                 memset(&hints, 0, sizeof(hints));
550                 hints.ai_family = AF_INET;
551                 hints.ai_protocol = IPPROTO_UDP;
552                 res = NULL;
553                 error = getaddrinfo(server, NULL, &hints, &res);
554                 if (error != 0)
555                         err(1, "%s", gai_strerror(error));
556                 if (res == NULL)
557                         errx(1, "failed to resolve '%s'", server);
558                 server = inet_ntoa(
559                     ((struct sockaddr_in *)(void *)res->ai_addr)->sin_addr);
560                 freeaddrinfo(res);
561
562                 if (strlcpy(ndconf.kda_iface, argv[0],
563                     sizeof(ndconf.kda_iface)) >= sizeof(ndconf.kda_iface))
564                         errx(EX_USAGE, "invalid interface name '%s'", argv[0]);
565                 if (inet_aton(server, &ndconf.kda_server.in4) == 0)
566                         errx(EX_USAGE, "invalid server address '%s'", server);
567                 if (inet_aton(client, &ndconf.kda_client.in4) == 0)
568                         errx(EX_USAGE, "invalid client address '%s'", client);
569
570                 if (gateway == NULL) {
571                         gateway = find_gateway(argv[0]);
572                         if (gateway == NULL) {
573                                 if (verbose)
574                                         printf(
575                                     "failed to look up gateway for %s\n",
576                                             server);
577                                 gateway = server;
578                         }
579                 }
580                 if (inet_aton(gateway, &ndconf.kda_gateway.in4) == 0)
581                         errx(EX_USAGE, "invalid gateway address '%s'", gateway);
582                 ndconf.kda_af = AF_INET;
583         }
584
585 #ifdef HAVE_CRYPTO
586         if (pubkeyfile != NULL) {
587                 kdap->kda_encryption = cipher;
588                 genkey(pubkeyfile, kdap);
589         }
590 #endif
591         error = ioctl(fd, DIOCSKERNELDUMP, kdap);
592         if (error != 0)
593                 error = errno;
594         if (error == EINVAL && (gzip || zstd)) {
595                 /* Retry without compression in case kernel lacks support. */
596                 kdap->kda_compression = KERNELDUMP_COMP_NONE;
597                 error = ioctl(fd, DIOCSKERNELDUMP, kdap);
598                 if (error == 0)
599                         warnx("Compression disabled; kernel may lack gzip or zstd support.");
600                 else
601                         error = errno;
602         }
603         /* Emit a warning if the user configured a downed interface. */
604         if (error == 0 && netdump)
605                 check_link_status(kdap->kda_iface);
606         explicit_bzero(kdap->kda_encryptedkey, kdap->kda_encryptedkeysize);
607         free(kdap->kda_encryptedkey);
608         explicit_bzero(kdap, sizeof(*kdap));
609         if (error != 0) {
610                 if (netdump) {
611                         /*
612                          * Be slightly less user-hostile for some common
613                          * errors, especially as users don't have any great
614                          * discoverability into which NICs support netdump.
615                          */
616                         if (error == ENODEV)
617                                 errx(EX_OSERR, "Unable to configure netdump "
618                                     "because the interface driver does not yet "
619                                     "support netdump.");
620                 }
621                 errc(EX_OSERR, error, "ioctl(DIOCSKERNELDUMP)");
622         }
623
624         if (verbose)
625                 listdumpdev();
626
627         exit(EX_OK);
628 }