1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Mike Muuss.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 /*
36 * P I N G . C
37 *
38 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
39 * measure round-trip-delays and packet loss across network paths.
40 *
41 * Author -
42 * Mike Muuss
43 * U. S. Army Ballistic Research Laboratory
44 * December, 1983
45 *
46 * Status -
47 * Public Domain. Distribution Unlimited.
48 * Bugs -
49 * More statistics could always be gathered.
50 * This program has to run SUID to ROOT to access the ICMP socket.
51 */
52
53 #include <sys/param.h> /* NB: we rely on this for <sys/types.h> */
54 #include <sys/capsicum.h>
55 #include <sys/socket.h>
56 #include <sys/sysctl.h>
57 #include <sys/time.h>
58 #include <sys/uio.h>
59
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/ip.h>
63 #include <netinet/ip_icmp.h>
64 #include <netinet/ip_var.h>
65 #include <arpa/inet.h>
66
67 #include <libcasper.h>
68 #include <casper/cap_dns.h>
69
70 #ifdef IPSEC
71 #include <netipsec/ipsec.h>
72 #endif /*IPSEC*/
73
74 #include <capsicum_helpers.h>
75 #include <ctype.h>
76 #include <err.h>
77 #include <errno.h>
78 #include <netdb.h>
79 #include <stddef.h>
80 #include <signal.h>
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <sysexits.h>
85 #include <time.h>
86 #include <unistd.h>
87
88 #include "main.h"
89 #include "ping.h"
90 #include "utils.h"
91
92 #define INADDR_LEN ((int)sizeof(in_addr_t))
93 #define TIMEVAL_LEN ((int)sizeof(struct tv32))
94 #define MASK_LEN (ICMP_MASKLEN - ICMP_MINLEN)
95 #define TS_LEN (ICMP_TSLEN - ICMP_MINLEN)
96 #define DEFDATALEN 56 /* default data length */
97 #define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */
98 /* runs out of buffer space */
99 #define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN)
100 #define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN)
101 #define MAXWAIT 10000 /* max ms to wait for response */
102 #define MAXALARM (60 * 60) /* max seconds for alarm timeout */
103 #define MAXTOS 255
104
105 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
106 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
107 #define SET(bit) (A(bit) |= B(bit))
108 #define CLR(bit) (A(bit) &= (~B(bit)))
109 #define TST(bit) (A(bit) & B(bit))
110
111 struct tv32 {
112 int32_t tv32_sec;
113 int32_t tv32_nsec;
114 };
115
116 /* various options */
117 #define F_FLOOD 0x0001
118 #define F_INTERVAL 0x0002
119 #define F_PINGFILLED 0x0008
120 #define F_QUIET 0x0010
121 #define F_RROUTE 0x0020
122 #define F_SO_DEBUG 0x0040
123 #define F_SO_DONTROUTE 0x0080
124 #define F_VERBOSE 0x0100
125 #define F_QUIET2 0x0200
126 #define F_NOLOOP 0x0400
127 #define F_MTTL 0x0800
128 #define F_MIF 0x1000
129 #define F_AUDIBLE 0x2000
130 #ifdef IPSEC
131 #ifdef IPSEC_POLICY_IPSEC
132 #define F_POLICY 0x4000
133 #endif /*IPSEC_POLICY_IPSEC*/
134 #endif /*IPSEC*/
135 #define F_TTL 0x8000
136 #define F_MISSED 0x10000
137 #define F_ONCE 0x20000
138 #define F_HDRINCL 0x40000
139 #define F_MASK 0x80000
140 #define F_TIME 0x100000
141 #define F_SWEEP 0x200000
142 #define F_WAITTIME 0x400000
143 #define F_IP_VLAN_PCP 0x800000
144 #define F_DOT 0x1000000
145
146 /*
147 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
148 * number of received sequence numbers we can keep track of. Change 128
149 * to 8192 for complete accuracy...
150 */
151 #define MAX_DUP_CHK (8 * 128)
152 static int mx_dup_ck = MAX_DUP_CHK;
153 static char rcvd_tbl[MAX_DUP_CHK / 8];
154
155 static struct sockaddr_in whereto; /* who to ping */
156 static int datalen = DEFDATALEN;
157 static int maxpayload;
158 static int ssend; /* send socket file descriptor */
159 static int srecv; /* receive socket file descriptor */
160 static u_char outpackhdr[IP_MAXPACKET], *outpack;
161 static char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */
162 static char BSPACE = '\b'; /* characters written for flood */
163 static const char *DOT = ".";
164 static size_t DOTlen = 1;
165 static size_t DOTidx = 0;
166 static char *shostname;
167 static int ident; /* process id to identify our packets */
168 static int uid; /* cached uid for micro-optimization */
169 static u_char icmp_type = ICMP_ECHO;
170 static u_char icmp_type_rsp = ICMP_ECHOREPLY;
171 static int phdr_len = 0;
172 static int send_len;
173
174 /* counters */
175 static long nmissedmax; /* max value of ntransmitted - nreceived - 1 */
176 static long npackets; /* max packets to transmit */
177 static long snpackets; /* max packets to transmit in one sweep */
178 static long sntransmitted; /* # of packets we sent in this sweep */
179 static int sweepmax; /* max value of payload in sweep */
180 static int sweepmin = 0; /* start value of payload in sweep */
181 static int sweepincr = 1; /* payload increment in sweep */
182 static int interval = 1000; /* interval between packets, ms */
183 static int waittime = MAXWAIT; /* timeout for each packet */
184
185 static cap_channel_t *capdns;
186
187 static void fill(char *, char *);
188 static cap_channel_t *capdns_setup(void);
189 static void pinger(void);
190 static char *pr_addr(struct in_addr);
191 static char *pr_ntime(n_time);
192 static void pr_icmph(struct icmp *, struct ip *, const u_char *const);
193 static void pr_iph(struct ip *, const u_char *);
194 static void pr_pack(char *, ssize_t, struct sockaddr_in *, struct timespec *);
195
196 int
ping(int argc,char * const * argv)197 ping(int argc, char *const *argv)
198 {
199 struct sockaddr_in from, sock_in;
200 struct in_addr ifaddr;
201 struct timespec last, intvl;
202 struct iovec iov;
203 struct msghdr msg;
204 struct sigaction si_sa;
205 size_t sz;
206 u_char *datap, packet[IP_MAXPACKET] __aligned(4);
207 const char *errstr;
208 char *ep, *source, *target, *payload;
209 struct hostent *hp;
210 #ifdef IPSEC_POLICY_IPSEC
211 char *policy_in, *policy_out;
212 #endif
213 struct sockaddr_in *to;
214 double t;
215 u_long alarmtimeout;
216 long long ltmp;
217 int almost_done, ch, df, hold, i, icmp_len, mib[4], preload;
218 int ssend_errno, srecv_errno, tos, ttl, pcp;
219 char ctrl[CMSG_SPACE(sizeof(struct timespec))];
220 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
221 #ifdef IP_OPTIONS
222 char rspace[MAX_IPOPTLEN]; /* record route space */
223 #endif
224 unsigned char loop, mttl;
225
226 payload = source = NULL;
227 #ifdef IPSEC_POLICY_IPSEC
228 policy_in = policy_out = NULL;
229 #endif
230 cap_rights_t rights;
231
232 /*
233 * Do the stuff that we need root priv's for *first*, and
234 * then drop our setuid bit. Save error reporting for
235 * after arg parsing.
236 *
237 * Historicaly ping was using one socket 's' for sending and for
238 * receiving. After capsicum(4) related changes we use two
239 * sockets. It was done for special ping use case - when user
240 * issue ping on multicast or broadcast address replies come
241 * from different addresses, not from the address we
242 * connect(2)'ed to, and send socket do not receive those
243 * packets.
244 */
245 ssend = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
246 ssend_errno = errno;
247 srecv = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
248 srecv_errno = errno;
249
250 if (setuid(getuid()) != 0)
251 err(EX_NOPERM, "setuid() failed");
252 uid = getuid();
253
254 if (ssend < 0) {
255 errno = ssend_errno;
256 err(EX_OSERR, "ssend socket");
257 }
258
259 if (srecv < 0) {
260 errno = srecv_errno;
261 err(EX_OSERR, "srecv socket");
262 }
263
264 alarmtimeout = df = preload = tos = pcp = 0;
265
266 outpack = outpackhdr + sizeof(struct ip);
267 while ((ch = getopt(argc, argv, PING4OPTS)) != -1) {
268 switch(ch) {
269 case '.':
270 options |= F_DOT;
271 if (optarg != NULL) {
272 DOT = optarg;
273 DOTlen = strlen(optarg);
274 }
275 break;
276 case '4':
277 /* This option is processed in main(). */
278 break;
279 case 'A':
280 options |= F_MISSED;
281 break;
282 case 'a':
283 options |= F_AUDIBLE;
284 break;
285 case 'C':
286 options |= F_IP_VLAN_PCP;
287 ltmp = strtonum(optarg, -1, 7, &errstr);
288 if (errstr != NULL)
289 errx(EX_USAGE, "invalid PCP: `%s'", optarg);
290 pcp = ltmp;
291 break;
292 case 'c':
293 ltmp = strtonum(optarg, 1, LONG_MAX, &errstr);
294 if (errstr != NULL)
295 errx(EX_USAGE,
296 "invalid count of packets to transmit: `%s'",
297 optarg);
298 npackets = (long)ltmp;
299 break;
300 case 'D':
301 options |= F_HDRINCL;
302 df = 1;
303 break;
304 case 'd':
305 options |= F_SO_DEBUG;
306 break;
307 case 'f':
308 if (uid) {
309 errno = EPERM;
310 err(EX_NOPERM, "-f flag");
311 }
312 options |= F_FLOOD;
313 options |= F_DOT;
314 setbuf(stdout, (char *)NULL);
315 break;
316 case 'G': /* Maximum payload size for ping sweep */
317 ltmp = strtonum(optarg, 1, INT_MAX, &errstr);
318 if (errstr != NULL) {
319 errx(EX_USAGE, "invalid payload size: `%s'",
320 optarg);
321 }
322 sweepmax = (int)ltmp;
323 if (uid != 0 && sweepmax > DEFDATALEN) {
324 errc(EX_NOPERM, EPERM,
325 "payload size too large: %d > %u",
326 sweepmax, DEFDATALEN);
327 }
328 options |= F_SWEEP;
329 break;
330 case 'g': /* Minimum payload size for ping sweep */
331 ltmp = strtonum(optarg, 0, INT_MAX, &errstr);
332 if (errstr != NULL) {
333 errx(EX_USAGE, "invalid payload size: `%s'",
334 optarg);
335 }
336 sweepmin = (int)ltmp;
337 if (uid != 0 && sweepmin > DEFDATALEN) {
338 errc(EX_NOPERM, EPERM,
339 "payload size too large: %d > %u",
340 sweepmin, DEFDATALEN);
341 }
342 options |= F_SWEEP;
343 break;
344 case 'H':
345 options |= F_HOSTNAME;
346 break;
347 case 'h': /* Payload size increment for ping sweep */
348 ltmp = strtonum(optarg, 1, INT_MAX, &errstr);
349 if (errstr != NULL) {
350 errx(EX_USAGE, "invalid payload size: `%s'",
351 optarg);
352 }
353 sweepincr = (int)ltmp;
354 if (uid != 0 && sweepincr > DEFDATALEN) {
355 errc(EX_NOPERM, EPERM,
356 "payload size too large: %d > %u",
357 sweepincr, DEFDATALEN);
358 }
359 options |= F_SWEEP;
360 break;
361 case 'I': /* multicast interface */
362 if (inet_aton(optarg, &ifaddr) == 0)
363 errx(EX_USAGE,
364 "invalid multicast interface: `%s'",
365 optarg);
366 options |= F_MIF;
367 break;
368 case 'i': /* wait between sending packets */
369 t = strtod(optarg, &ep) * 1000.0;
370 if (*ep || ep == optarg || t > (double)INT_MAX)
371 errx(EX_USAGE, "invalid timing interval: `%s'",
372 optarg);
373 options |= F_INTERVAL;
374 interval = (int)t;
375 if (uid && interval < 1000) {
376 errno = EPERM;
377 err(EX_NOPERM, "-i interval too short");
378 }
379 break;
380 case 'L':
381 options |= F_NOLOOP;
382 loop = 0;
383 break;
384 case 'l':
385 ltmp = strtonum(optarg, 0, INT_MAX, &errstr);
386 if (errstr != NULL)
387 errx(EX_USAGE,
388 "invalid preload value: `%s'", optarg);
389 if (uid) {
390 errno = EPERM;
391 err(EX_NOPERM, "-l flag");
392 }
393 preload = (int)ltmp;
394 break;
395 case 'M':
396 switch(optarg[0]) {
397 case 'M':
398 case 'm':
399 options |= F_MASK;
400 break;
401 case 'T':
402 case 't':
403 options |= F_TIME;
404 break;
405 default:
406 errx(EX_USAGE, "invalid message: `%c'", optarg[0]);
407 break;
408 }
409 break;
410 case 'm': /* TTL */
411 ltmp = strtonum(optarg, 0, MAXTTL, &errstr);
412 if (errstr != NULL)
413 errx(EX_USAGE, "invalid TTL: `%s'", optarg);
414 ttl = (int)ltmp;
415 options |= F_TTL;
416 break;
417 case 'n':
418 options &= ~F_HOSTNAME;
419 break;
420 case 'o':
421 options |= F_ONCE;
422 break;
423 #ifdef IPSEC
424 #ifdef IPSEC_POLICY_IPSEC
425 case 'P':
426 options |= F_POLICY;
427 if (!strncmp("in", optarg, 2))
428 policy_in = strdup(optarg);
429 else if (!strncmp("out", optarg, 3))
430 policy_out = strdup(optarg);
431 else
432 errx(1, "invalid security policy");
433 break;
434 #endif /*IPSEC_POLICY_IPSEC*/
435 #endif /*IPSEC*/
436 case 'p': /* fill buffer with user pattern */
437 options |= F_PINGFILLED;
438 payload = optarg;
439 break;
440 case 'Q':
441 options |= F_QUIET2;
442 break;
443 case 'q':
444 options |= F_QUIET;
445 break;
446 case 'R':
447 options |= F_RROUTE;
448 break;
449 case 'r':
450 options |= F_SO_DONTROUTE;
451 break;
452 case 'S':
453 source = optarg;
454 break;
455 case 's': /* size of packet to send */
456 ltmp = strtonum(optarg, 0, INT_MAX, &errstr);
457 if (errstr != NULL)
458 errx(EX_USAGE, "invalid packet size: `%s'",
459 optarg);
460 datalen = (int)ltmp;
461 if (uid != 0 && datalen > DEFDATALEN) {
462 errno = EPERM;
463 err(EX_NOPERM,
464 "packet size too large: %d > %u",
465 datalen, DEFDATALEN);
466 }
467 break;
468 case 'T': /* multicast TTL */
469 ltmp = strtonum(optarg, 0, MAXTTL, &errstr);
470 if (errstr != NULL)
471 errx(EX_USAGE, "invalid multicast TTL: `%s'",
472 optarg);
473 mttl = (unsigned char)ltmp;
474 options |= F_MTTL;
475 break;
476 case 't':
477 alarmtimeout = strtoul(optarg, &ep, 0);
478 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
479 errx(EX_USAGE, "invalid timeout: `%s'",
480 optarg);
481 if (alarmtimeout > MAXALARM)
482 errx(EX_USAGE, "invalid timeout: `%s' > %d",
483 optarg, MAXALARM);
484 {
485 struct itimerval itv;
486
487 timerclear(&itv.it_interval);
488 timerclear(&itv.it_value);
489 itv.it_value.tv_sec = (time_t)alarmtimeout;
490 if (setitimer(ITIMER_REAL, &itv, NULL) != 0)
491 err(1, "setitimer");
492 }
493 break;
494 case 'v':
495 options |= F_VERBOSE;
496 break;
497 case 'W': /* wait ms for answer */
498 t = strtod(optarg, &ep);
499 if (*ep || ep == optarg || t > (double)INT_MAX)
500 errx(EX_USAGE, "invalid timing interval: `%s'",
501 optarg);
502 options |= F_WAITTIME;
503 waittime = (int)t;
504 break;
505 case 'z':
506 options |= F_HDRINCL;
507 ltmp = strtol(optarg, &ep, 0);
508 if (*ep || ep == optarg || ltmp > MAXTOS || ltmp < 0)
509 errx(EX_USAGE, "invalid TOS: `%s'", optarg);
510 tos = ltmp;
511 break;
512 default:
513 usage();
514 }
515 }
516
517 if (argc - optind != 1)
518 usage();
519 target = argv[optind];
520
521 switch (options & (F_MASK|F_TIME)) {
522 case 0: break;
523 case F_MASK:
524 icmp_type = ICMP_MASKREQ;
525 icmp_type_rsp = ICMP_MASKREPLY;
526 phdr_len = MASK_LEN;
527 if (!(options & F_QUIET))
528 (void)printf("ICMP_MASKREQ\n");
529 break;
530 case F_TIME:
531 icmp_type = ICMP_TSTAMP;
532 icmp_type_rsp = ICMP_TSTAMPREPLY;
533 phdr_len = TS_LEN;
534 if (!(options & F_QUIET))
535 (void)printf("ICMP_TSTAMP\n");
536 break;
537 default:
538 errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive.");
539 break;
540 }
541 icmp_len = sizeof(struct ip) + ICMP_MINLEN + phdr_len;
542 if (options & F_RROUTE)
543 icmp_len += MAX_IPOPTLEN;
544 maxpayload = IP_MAXPACKET - icmp_len;
545 if (datalen > maxpayload)
546 errx(EX_USAGE, "packet size too large: %d > %d", datalen,
547 maxpayload);
548 send_len = icmp_len + datalen;
549 datap = &outpack[ICMP_MINLEN + phdr_len + TIMEVAL_LEN];
550 if (options & F_PINGFILLED) {
551 fill((char *)datap, payload);
552 }
553 capdns = capdns_setup();
554 if (source) {
555 bzero((char *)&sock_in, sizeof(sock_in));
556 sock_in.sin_family = AF_INET;
557 if (inet_aton(source, &sock_in.sin_addr) != 0) {
558 shostname = source;
559 } else {
560 hp = cap_gethostbyname2(capdns, source, AF_INET);
561 if (!hp)
562 errx(EX_NOHOST, "cannot resolve %s: %s",
563 source, hstrerror(h_errno));
564
565 sock_in.sin_len = sizeof sock_in;
566 if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) ||
567 hp->h_length < 0)
568 errx(1, "gethostbyname2: illegal address");
569 memcpy(&sock_in.sin_addr, hp->h_addr_list[0],
570 sizeof(sock_in.sin_addr));
571 (void)strncpy(snamebuf, hp->h_name,
572 sizeof(snamebuf) - 1);
573 snamebuf[sizeof(snamebuf) - 1] = '\0';
574 shostname = snamebuf;
575 }
576 if (bind(ssend, (struct sockaddr *)&sock_in, sizeof sock_in) ==
577 -1)
578 err(1, "bind");
579 }
580
581 bzero(&whereto, sizeof(whereto));
582 to = &whereto;
583 to->sin_family = AF_INET;
584 to->sin_len = sizeof *to;
585 if (inet_aton(target, &to->sin_addr) != 0) {
586 hostname = target;
587 } else {
588 hp = cap_gethostbyname2(capdns, target, AF_INET);
589 if (!hp)
590 errx(EX_NOHOST, "cannot resolve %s: %s",
591 target, hstrerror(h_errno));
592
593 if ((unsigned)hp->h_length > sizeof(to->sin_addr))
594 errx(1, "gethostbyname2 returned an illegal address");
595 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
596 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
597 hnamebuf[sizeof(hnamebuf) - 1] = '\0';
598 hostname = hnamebuf;
599 }
600
601 /* From now on we will use only reverse DNS lookups. */
602 #ifdef WITH_CASPER
603 if (capdns != NULL) {
604 const char *types[1];
605
606 types[0] = "ADDR2NAME";
607 if (cap_dns_type_limit(capdns, types, 1) < 0)
608 err(1, "unable to limit access to system.dns service");
609 }
610 #endif
611 if (connect(ssend, (struct sockaddr *)&whereto, sizeof(whereto)) != 0)
612 err(1, "connect");
613
614 if (options & F_FLOOD && options & F_INTERVAL)
615 errx(EX_USAGE, "-f and -i: incompatible options");
616
617 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
618 errx(EX_USAGE,
619 "-f flag cannot be used with multicast destination");
620 if (options & (F_MIF | F_NOLOOP | F_MTTL)
621 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
622 errx(EX_USAGE,
623 "-I, -L, -T flags cannot be used with unicast destination");
624
625 if (datalen >= TIMEVAL_LEN) /* can we time transfer */
626 timing = 1;
627
628 if ((options & (F_PINGFILLED | F_SWEEP)) == 0)
629 for (i = TIMEVAL_LEN; i < datalen; ++i)
630 *datap++ = i;
631
632 ident = getpid() & 0xFFFF;
633
634 hold = 1;
635 if (options & F_SO_DEBUG) {
636 (void)setsockopt(ssend, SOL_SOCKET, SO_DEBUG, (char *)&hold,
637 sizeof(hold));
638 (void)setsockopt(srecv, SOL_SOCKET, SO_DEBUG, (char *)&hold,
639 sizeof(hold));
640 }
641 if (options & F_SO_DONTROUTE)
642 (void)setsockopt(ssend, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
643 sizeof(hold));
644 if (options & F_IP_VLAN_PCP) {
645 (void)setsockopt(ssend, IPPROTO_IP, IP_VLAN_PCP, (char *)&pcp,
646 sizeof(pcp));
647 }
648 #ifdef IPSEC
649 #ifdef IPSEC_POLICY_IPSEC
650 if (options & F_POLICY) {
651 char *buf;
652 if (policy_in != NULL) {
653 buf = ipsec_set_policy(policy_in, strlen(policy_in));
654 if (buf == NULL)
655 errx(EX_CONFIG, "%s", ipsec_strerror());
656 if (setsockopt(srecv, IPPROTO_IP, IP_IPSEC_POLICY,
657 buf, ipsec_get_policylen(buf)) < 0)
658 err(EX_CONFIG,
659 "ipsec policy cannot be configured");
660 free(buf);
661 }
662
663 if (policy_out != NULL) {
664 buf = ipsec_set_policy(policy_out, strlen(policy_out));
665 if (buf == NULL)
666 errx(EX_CONFIG, "%s", ipsec_strerror());
667 if (setsockopt(ssend, IPPROTO_IP, IP_IPSEC_POLICY,
668 buf, ipsec_get_policylen(buf)) < 0)
669 err(EX_CONFIG,
670 "ipsec policy cannot be configured");
671 free(buf);
672 }
673 }
674 #endif /*IPSEC_POLICY_IPSEC*/
675 #endif /*IPSEC*/
676
677 if (options & F_HDRINCL) {
678 struct ip ip;
679
680 memcpy(&ip, outpackhdr, sizeof(ip));
681 if (!(options & (F_TTL | F_MTTL))) {
682 mib[0] = CTL_NET;
683 mib[1] = PF_INET;
684 mib[2] = IPPROTO_IP;
685 mib[3] = IPCTL_DEFTTL;
686 sz = sizeof(ttl);
687 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1)
688 err(1, "sysctl(net.inet.ip.ttl)");
689 }
690 setsockopt(ssend, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
691 ip.ip_v = IPVERSION;
692 ip.ip_hl = sizeof(struct ip) >> 2;
693 ip.ip_tos = tos;
694 ip.ip_id = 0;
695 ip.ip_off = htons(df ? IP_DF : 0);
696 ip.ip_ttl = ttl;
697 ip.ip_p = IPPROTO_ICMP;
698 ip.ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY;
699 ip.ip_dst = to->sin_addr;
700 memcpy(outpackhdr, &ip, sizeof(ip));
701 }
702
703 /*
704 * Here we enter capability mode. Further down access to global
705 * namespaces (e.g filesystem) is restricted (see capsicum(4)).
706 * We must connect(2) our socket before this point.
707 */
708 caph_cache_catpages();
709 if (caph_enter_casper() < 0)
710 err(1, "caph_enter_casper");
711
712 cap_rights_init(&rights, CAP_RECV, CAP_EVENT, CAP_SETSOCKOPT);
713 if (caph_rights_limit(srecv, &rights) < 0)
714 err(1, "cap_rights_limit srecv");
715 cap_rights_init(&rights, CAP_SEND, CAP_SETSOCKOPT);
716 if (caph_rights_limit(ssend, &rights) < 0)
717 err(1, "cap_rights_limit ssend");
718
719 /* record route option */
720 if (options & F_RROUTE) {
721 #ifdef IP_OPTIONS
722 bzero(rspace, sizeof(rspace));
723 rspace[IPOPT_OPTVAL] = IPOPT_RR;
724 rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
725 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
726 rspace[sizeof(rspace) - 1] = IPOPT_EOL;
727 if (setsockopt(ssend, IPPROTO_IP, IP_OPTIONS, rspace,
728 sizeof(rspace)) < 0)
729 err(EX_OSERR, "setsockopt IP_OPTIONS");
730 #else
731 errx(EX_UNAVAILABLE,
732 "record route not available in this implementation");
733 #endif /* IP_OPTIONS */
734 }
735
736 if (options & F_TTL) {
737 if (setsockopt(ssend, IPPROTO_IP, IP_TTL, &ttl,
738 sizeof(ttl)) < 0) {
739 err(EX_OSERR, "setsockopt IP_TTL");
740 }
741 }
742 if (options & F_NOLOOP) {
743 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
744 sizeof(loop)) < 0) {
745 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
746 }
747 }
748 if (options & F_MTTL) {
749 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
750 sizeof(mttl)) < 0) {
751 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
752 }
753 }
754 if (options & F_MIF) {
755 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
756 sizeof(ifaddr)) < 0) {
757 err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
758 }
759 }
760 #ifdef SO_TIMESTAMP
761 {
762 int on = 1;
763 int ts_clock = SO_TS_MONOTONIC;
764 if (setsockopt(srecv, SOL_SOCKET, SO_TIMESTAMP, &on,
765 sizeof(on)) < 0)
766 err(EX_OSERR, "setsockopt SO_TIMESTAMP");
767 if (setsockopt(srecv, SOL_SOCKET, SO_TS_CLOCK, &ts_clock,
768 sizeof(ts_clock)) < 0)
769 err(EX_OSERR, "setsockopt SO_TS_CLOCK");
770 }
771 #endif
772 if (sweepmax) {
773 if (sweepmin > sweepmax)
774 errx(EX_USAGE,
775 "Maximum packet size must be no less than the minimum packet size");
776
777 if (sweepmax > maxpayload - TIMEVAL_LEN)
778 errx(EX_USAGE, "Invalid sweep maximum");
779
780 if (datalen != DEFDATALEN)
781 errx(EX_USAGE,
782 "Packet size and ping sweep are mutually exclusive");
783
784 if (npackets > 0) {
785 snpackets = npackets;
786 npackets = 0;
787 } else
788 snpackets = 1;
789 datalen = sweepmin;
790 send_len = icmp_len + sweepmin;
791 }
792 if (options & F_SWEEP && !sweepmax)
793 errx(EX_USAGE, "Maximum sweep size must be specified");
794
795 /*
796 * When pinging the broadcast address, you can get a lot of answers.
797 * Doing something so evil is useful if you are trying to stress the
798 * ethernet, or just want to fill the arp cache to get some stuff for
799 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast
800 * or multicast pings if they wish.
801 */
802
803 /*
804 * XXX receive buffer needs undetermined space for mbuf overhead
805 * as well.
806 */
807 hold = IP_MAXPACKET + 128;
808 (void)setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
809 sizeof(hold));
810 /* CAP_SETSOCKOPT removed */
811 cap_rights_init(&rights, CAP_RECV, CAP_EVENT);
812 if (caph_rights_limit(srecv, &rights) < 0)
813 err(1, "cap_rights_limit srecv setsockopt");
814 if (uid == 0)
815 (void)setsockopt(ssend, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
816 sizeof(hold));
817 /* CAP_SETSOCKOPT removed */
818 cap_rights_init(&rights, CAP_SEND);
819 if (caph_rights_limit(ssend, &rights) < 0)
820 err(1, "cap_rights_limit ssend setsockopt");
821
822 if (to->sin_family == AF_INET) {
823 (void)printf("PING %s (%s)", hostname,
824 inet_ntoa(to->sin_addr));
825 if (source)
826 (void)printf(" from %s", shostname);
827 if (sweepmax)
828 (void)printf(": (%d ... %d) data bytes\n",
829 sweepmin, sweepmax);
830 else
831 (void)printf(": %d data bytes\n", datalen);
832 } else {
833 if (sweepmax)
834 (void)printf("PING %s: (%d ... %d) data bytes\n",
835 hostname, sweepmin, sweepmax);
836 else
837 (void)printf("PING %s: %d data bytes\n", hostname, datalen);
838 }
839 (void)fflush(stdout);
840
841 /*
842 * Use sigaction() instead of signal() to get unambiguous semantics,
843 * in particular with SA_RESTART not set.
844 */
845
846 sigemptyset(&si_sa.sa_mask);
847 si_sa.sa_flags = 0;
848 si_sa.sa_handler = onsignal;
849 if (sigaction(SIGINT, &si_sa, 0) == -1)
850 err(EX_OSERR, "sigaction SIGINT");
851 seenint = 0;
852 if (sigaction(SIGINFO, &si_sa, 0) == -1)
853 err(EX_OSERR, "sigaction SIGINFO");
854 seeninfo = 0;
855 if (alarmtimeout > 0) {
856 if (sigaction(SIGALRM, &si_sa, 0) == -1)
857 err(EX_OSERR, "sigaction SIGALRM");
858 }
859
860 bzero(&msg, sizeof(msg));
861 msg.msg_name = (caddr_t)&from;
862 msg.msg_iov = &iov;
863 msg.msg_iovlen = 1;
864 #ifdef SO_TIMESTAMP
865 msg.msg_control = (caddr_t)ctrl;
866 msg.msg_controllen = sizeof(ctrl);
867 #endif
868 iov.iov_base = packet;
869 iov.iov_len = IP_MAXPACKET;
870
871 if (preload == 0)
872 pinger(); /* send the first ping */
873 else {
874 if (npackets != 0 && preload > npackets)
875 preload = npackets;
876 while (preload--) /* fire off them quickies */
877 pinger();
878 }
879 (void)clock_gettime(CLOCK_MONOTONIC, &last);
880
881 if (options & F_FLOOD) {
882 intvl.tv_sec = 0;
883 intvl.tv_nsec = 10000000;
884 } else {
885 intvl.tv_sec = interval / 1000;
886 intvl.tv_nsec = interval % 1000 * 1000000;
887 }
888
889 almost_done = 0;
890 while (seenint == 0) {
891 struct timespec now, timeout;
892 fd_set rfds;
893 int n;
894 ssize_t cc;
895
896 /* signal handling */
897 if (seeninfo) {
898 pr_summary(stderr);
899 seeninfo = 0;
900 continue;
901 }
902 if ((unsigned)srecv >= FD_SETSIZE)
903 errx(EX_OSERR, "descriptor too large");
904 FD_ZERO(&rfds);
905 FD_SET(srecv, &rfds);
906 (void)clock_gettime(CLOCK_MONOTONIC, &now);
907 timespecadd(&last, &intvl, &timeout);
908 timespecsub(&timeout, &now, &timeout);
909 if (timeout.tv_sec < 0)
910 timespecclear(&timeout);
911
912 n = pselect(srecv + 1, &rfds, NULL, NULL, &timeout, NULL);
913 if (n < 0)
914 continue; /* EINTR */
915 if (n == 1) {
916 struct timespec *tv = NULL;
917 #ifdef SO_TIMESTAMP
918 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
919 #endif
920 msg.msg_namelen = sizeof(from);
921 if ((cc = recvmsg(srecv, &msg, 0)) < 0) {
922 if (errno == EINTR)
923 continue;
924 warn("recvmsg");
925 continue;
926 }
927 /* If we have a 0 byte read from recvfrom continue */
928 if (cc == 0)
929 continue;
930 #ifdef SO_TIMESTAMP
931 if (cmsg != NULL &&
932 cmsg->cmsg_level == SOL_SOCKET &&
933 cmsg->cmsg_type == SCM_TIMESTAMP &&
934 cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) {
935 /* Copy to avoid alignment problems: */
936 memcpy(&now, CMSG_DATA(cmsg), sizeof(now));
937 tv = &now;
938 }
939 #endif
940 if (tv == NULL) {
941 (void)clock_gettime(CLOCK_MONOTONIC, &now);
942 tv = &now;
943 }
944 pr_pack((char *)packet, cc, &from, tv);
945 if ((options & F_ONCE && nreceived) ||
946 (npackets && nreceived >= npackets))
947 break;
948 }
949 if (n == 0 || (options & F_FLOOD)) {
950 if (sweepmax && sntransmitted == snpackets) {
951 if (datalen + sweepincr > sweepmax)
952 break;
953 for (i = 0; i < sweepincr; i++)
954 *datap++ = i;
955 datalen += sweepincr;
956 send_len = icmp_len + datalen;
957 sntransmitted = 0;
958 }
959 if (!npackets || ntransmitted < npackets)
960 pinger();
961 else {
962 if (almost_done)
963 break;
964 almost_done = 1;
965 /*
966 * If we're not transmitting any more packets,
967 * change the timer to wait two round-trip times
968 * if we've received any packets or (waittime)
969 * milliseconds if we haven't.
970 */
971 intvl.tv_nsec = 0;
972 if (nreceived) {
973 intvl.tv_sec = 2 * tmax / 1000;
974 if (intvl.tv_sec == 0)
975 intvl.tv_sec = 1;
976 } else {
977 intvl.tv_sec = waittime / 1000;
978 intvl.tv_nsec =
979 waittime % 1000 * 1000000;
980 }
981 }
982 (void)clock_gettime(CLOCK_MONOTONIC, &last);
983 if (ntransmitted - nreceived - 1 > nmissedmax) {
984 nmissedmax = ntransmitted - nreceived - 1;
985 if (options & F_MISSED) {
986 (void)putc(BBELL, stdout);
987 (void)fflush(stdout);
988 }
989 }
990 }
991 }
992 pr_summary(stdout);
993
994 exit(nreceived ? 0 : 2);
995 }
996
997 /*
998 * pinger --
999 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
1000 * will be added on by the kernel. The ID field is our UNIX process ID,
1001 * and the sequence number is an ascending integer. The first TIMEVAL_LEN
1002 * bytes of the data portion are used to hold a UNIX "timespec" struct in
1003 * host byte-order, to compute the round-trip time.
1004 */
1005 static void
pinger(void)1006 pinger(void)
1007 {
1008 struct timespec now;
1009 struct tv32 tv32;
1010 struct icmp icp;
1011 int cc, i;
1012 u_char *packet;
1013
1014 packet = outpack;
1015 memcpy(&icp, outpack, ICMP_MINLEN + phdr_len);
1016 icp.icmp_type = icmp_type;
1017 icp.icmp_code = 0;
1018 icp.icmp_cksum = 0;
1019 icp.icmp_seq = htons(ntransmitted);
1020 icp.icmp_id = ident; /* ID */
1021
1022 CLR(ntransmitted % mx_dup_ck);
1023
1024 if ((options & F_TIME) || timing) {
1025 (void)clock_gettime(CLOCK_MONOTONIC, &now);
1026 /*
1027 * Truncate seconds down to 32 bits in order
1028 * to fit the timestamp within 8 bytes of the
1029 * packet. We're only concerned with
1030 * durations, not absolute times.
1031 */
1032 tv32.tv32_sec = (uint32_t)htonl(now.tv_sec);
1033 tv32.tv32_nsec = (uint32_t)htonl(now.tv_nsec);
1034 if (options & F_TIME) {
1035 /*
1036 * However, per RFC 792 the Originate Timestamp (otime)
1037 * should be milliseconds since midnight UTC. Something,
1038 * that CLOCK_MONOTONIC does not guarantee.
1039 */
1040 (void)clock_gettime(CLOCK_REALTIME, &now);
1041 icp.icmp_otime = htonl((now.tv_sec % (24*60*60))
1042 * 1000 + now.tv_nsec / 1000000);
1043 }
1044 if (timing)
1045 bcopy((void *)&tv32,
1046 (void *)&outpack[ICMP_MINLEN + phdr_len],
1047 sizeof(tv32));
1048 }
1049
1050 memcpy(outpack, &icp, ICMP_MINLEN + phdr_len);
1051
1052 cc = ICMP_MINLEN + phdr_len + datalen;
1053
1054 /* compute ICMP checksum here */
1055 icp.icmp_cksum = in_cksum(outpack, cc);
1056 /* Update icmp_cksum in the raw packet data buffer. */
1057 memcpy(outpack + offsetof(struct icmp, icmp_cksum), &icp.icmp_cksum,
1058 sizeof(icp.icmp_cksum));
1059
1060 if (options & F_HDRINCL) {
1061 struct ip ip;
1062
1063 cc += sizeof(struct ip);
1064 ip.ip_len = htons(cc);
1065 /* Update ip_len in the raw packet data buffer. */
1066 memcpy(outpackhdr + offsetof(struct ip, ip_len), &ip.ip_len,
1067 sizeof(ip.ip_len));
1068 ip.ip_sum = in_cksum(outpackhdr, cc);
1069 /* Update ip_sum in the raw packet data buffer. */
1070 memcpy(outpackhdr + offsetof(struct ip, ip_sum), &ip.ip_sum,
1071 sizeof(ip.ip_sum));
1072 packet = outpackhdr;
1073 }
1074 i = send(ssend, (char *)packet, cc, 0);
1075 if (i < 0 || i != cc) {
1076 if (i < 0) {
1077 if (options & F_FLOOD && errno == ENOBUFS) {
1078 usleep(FLOOD_BACKOFF);
1079 return;
1080 }
1081 warn("sendto");
1082 } else {
1083 warn("%s: partial write: %d of %d bytes",
1084 hostname, i, cc);
1085 }
1086 }
1087 ntransmitted++;
1088 sntransmitted++;
1089 if (!(options & F_QUIET) && options & F_DOT) {
1090 (void)putc(DOT[DOTidx++ % DOTlen], stdout);
1091 (void)fflush(stdout);
1092 }
1093 }
1094
1095 /*
1096 * pr_pack --
1097 * Print out the packet, if it came from us. This logic is necessary
1098 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1099 * which arrive ('tis only fair). This permits multiple copies of this
1100 * program to be run without having intermingled output (or statistics!).
1101 */
1102 static void
pr_pack(char * buf,ssize_t cc,struct sockaddr_in * from,struct timespec * tv)1103 pr_pack(char *buf, ssize_t cc, struct sockaddr_in *from, struct timespec *tv)
1104 {
1105 struct in_addr ina;
1106 u_char *cp, *dp, l;
1107 struct icmp icp;
1108 struct ip ip;
1109 const u_char *icmp_data_raw;
1110 ssize_t icmp_data_raw_len;
1111 double triptime;
1112 int avail, dupflag, i, j, recv_len;
1113 int8_t hlen;
1114 uint16_t seq;
1115 static int old_rrlen;
1116 static char old_rr[MAX_IPOPTLEN];
1117 struct ip oip;
1118 u_char oip_header_len;
1119 struct icmp oicmp;
1120 const u_char *oicmp_raw;
1121
1122 bzero(&icp, sizeof(icp));
1123 /*
1124 * Get size of IP header of the received packet.
1125 * The header length is contained in the lower four bits of the first
1126 * byte and represents the number of 4 byte octets the header takes up.
1127 *
1128 * The IHL minimum value is 5 (20 bytes) and its maximum value is 15
1129 * (60 bytes).
1130 */
1131 memcpy(&l, buf, sizeof(l));
1132 hlen = (l & 0x0f) << 2;
1133
1134 /* Reject IP packets with a short header */
1135 if (hlen < (int8_t) sizeof(struct ip)) {
1136 if (options & F_VERBOSE)
1137 warn("IHL too short (%d bytes) from %s", hlen,
1138 inet_ntoa(from->sin_addr));
1139 return;
1140 }
1141
1142 memcpy(&ip, buf, sizeof(struct ip));
1143
1144 /* Check packet has enough data to carry a valid ICMP header */
1145 recv_len = cc;
1146 if (cc < hlen + ICMP_MINLEN) {
1147 if (options & F_VERBOSE)
1148 warn("packet too short (%zd bytes) from %s", cc,
1149 inet_ntoa(from->sin_addr));
1150 return;
1151 }
1152
1153 icmp_data_raw_len = cc - (hlen + offsetof(struct icmp, icmp_data));
1154 icmp_data_raw = buf + hlen + offsetof(struct icmp, icmp_data);
1155
1156 /* Now the ICMP part */
1157 cc -= hlen;
1158 memcpy(&icp, buf + hlen, MIN((ssize_t)sizeof(icp), cc));
1159 if (icp.icmp_type == icmp_type_rsp) {
1160 if (icp.icmp_id != ident)
1161 return; /* 'Twas not our ECHO */
1162 if (icmp_type_rsp == ICMP_MASKREPLY &&
1163 cc < (ssize_t)(ICMP_MINLEN + MASK_LEN)) {
1164 if (options & F_VERBOSE)
1165 warnx("truncated mask reply (%zd bytes) from %s",
1166 cc, inet_ntoa(from->sin_addr));
1167 return;
1168 }
1169 if (icmp_type_rsp == ICMP_TSTAMPREPLY &&
1170 cc < (ssize_t)(ICMP_MINLEN + TS_LEN)) {
1171 if (options & F_VERBOSE)
1172 warnx("truncated timestamp reply (%zd bytes) from %s",
1173 cc, inet_ntoa(from->sin_addr));
1174 return;
1175 }
1176 ++nreceived;
1177 triptime = 0.0;
1178 if (timing) {
1179 struct timespec tv1;
1180 struct tv32 tv32;
1181 const u_char *tp;
1182
1183 tp = icmp_data_raw + phdr_len;
1184
1185 if ((size_t)(cc - ICMP_MINLEN - phdr_len) >=
1186 sizeof(tv1)) {
1187 /* Copy to avoid alignment problems: */
1188 memcpy(&tv32, tp, sizeof(tv32));
1189 tv1.tv_sec = ntohl(tv32.tv32_sec);
1190 tv1.tv_nsec = ntohl(tv32.tv32_nsec);
1191 timespecsub(tv, &tv1, tv);
1192 triptime = ((double)tv->tv_sec) * 1000.0 +
1193 ((double)tv->tv_nsec) / 1000000.0;
1194 if (triptime < 0) {
1195 warnx("time of day goes back (%.3f ms),"
1196 " clamping time to 0",
1197 triptime);
1198 triptime = 0;
1199 }
1200 tsum += triptime;
1201 tsumsq += triptime * triptime;
1202 if (triptime < tmin)
1203 tmin = triptime;
1204 if (triptime > tmax)
1205 tmax = triptime;
1206 } else
1207 timing = 0;
1208 }
1209
1210 seq = ntohs(icp.icmp_seq);
1211
1212 if (TST(seq % mx_dup_ck)) {
1213 ++nrepeats;
1214 --nreceived;
1215 dupflag = 1;
1216 } else {
1217 SET(seq % mx_dup_ck);
1218 dupflag = 0;
1219 }
1220
1221 if (options & F_QUIET)
1222 return;
1223
1224 if (options & F_WAITTIME && triptime > waittime) {
1225 ++nrcvtimeout;
1226 return;
1227 }
1228
1229 if (options & F_DOT) {
1230 (void)putc(BSPACE, stdout);
1231 (void)fflush(stdout);
1232 } else {
1233 (void)printf("%zd bytes from %s: icmp_seq=%u", cc,
1234 pr_addr(from->sin_addr), seq);
1235 (void)printf(" ttl=%d", ip.ip_ttl);
1236 if (timing)
1237 (void)printf(" time=%.3f ms", triptime);
1238 if (dupflag)
1239 (void)printf(" (DUP!)");
1240 if (options & F_AUDIBLE) {
1241 (void)putc(BBELL, stdout);
1242 (void)fflush(stdout);
1243 }
1244 if (options & F_MASK) {
1245 /* Just prentend this cast isn't ugly */
1246 (void)printf(" mask=%s",
1247 inet_ntoa(*(struct in_addr *)&(icp.icmp_mask)));
1248 }
1249 if (options & F_TIME) {
1250 (void)printf(" tso=%s", pr_ntime(icp.icmp_otime));
1251 (void)printf(" tsr=%s", pr_ntime(icp.icmp_rtime));
1252 (void)printf(" tst=%s", pr_ntime(icp.icmp_ttime));
1253 }
1254 if (recv_len != send_len) {
1255 (void)printf(
1256 "\nwrong total length %d instead of %d",
1257 recv_len, send_len);
1258 }
1259 /* check the data */
1260 cp = (u_char*)(buf + hlen + offsetof(struct icmp,
1261 icmp_data) + phdr_len);
1262 dp = &outpack[ICMP_MINLEN + phdr_len];
1263 cc -= ICMP_MINLEN + phdr_len;
1264 i = 0;
1265 if (timing) { /* don't check variable timestamp */
1266 cp += TIMEVAL_LEN;
1267 dp += TIMEVAL_LEN;
1268 cc -= TIMEVAL_LEN;
1269 i += TIMEVAL_LEN;
1270 }
1271 for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) {
1272 if (*cp != *dp) {
1273 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
1274 i, *dp, *cp);
1275 (void)printf("\ncp:");
1276 avail = (int)MIN((ssize_t)datalen,
1277 i + cc);
1278 cp = (u_char*)(buf + hlen +
1279 offsetof(struct icmp, icmp_data));
1280 for (i = 0; i < avail; ++i, ++cp) {
1281 if ((i % 16) == 8)
1282 (void)printf("\n\t");
1283 (void)printf(" %2x", *cp);
1284 }
1285 (void)printf("\ndp:");
1286 cp = &outpack[ICMP_MINLEN];
1287 for (i = 0; i < datalen; ++i, ++cp) {
1288 if ((i % 16) == 8)
1289 (void)printf("\n\t");
1290 (void)printf(" %2x", *cp);
1291 }
1292 break;
1293 }
1294 }
1295 }
1296 } else {
1297 /*
1298 * We've got something other than an ECHOREPLY.
1299 * See if it's a reply to something that we sent.
1300 * We can compare IP destination, protocol,
1301 * and ICMP type and ID.
1302 *
1303 * Only print all the error messages if we are running
1304 * as root to avoid leaking information not normally
1305 * available to those not running as root.
1306 */
1307
1308 /*
1309 * If we don't have enough bytes for a quoted IP header and an
1310 * ICMP header then stop.
1311 */
1312 if (icmp_data_raw_len <
1313 (ssize_t)(sizeof(struct ip) + sizeof(struct icmp))) {
1314 if (options & F_VERBOSE)
1315 warnx("quoted data too short (%zd bytes) from %s",
1316 icmp_data_raw_len, inet_ntoa(from->sin_addr));
1317 return;
1318 }
1319
1320 memcpy(&oip_header_len, icmp_data_raw, sizeof(oip_header_len));
1321 oip_header_len = (oip_header_len & 0x0f) << 2;
1322
1323 /* Reject IP packets with a short header */
1324 if (oip_header_len < sizeof(struct ip)) {
1325 if (options & F_VERBOSE)
1326 warnx("inner IHL too short (%d bytes) from %s",
1327 oip_header_len, inet_ntoa(from->sin_addr));
1328 return;
1329 }
1330
1331 /*
1332 * Check against the actual IHL length, to protect against
1333 * quoated packets carrying IP options.
1334 */
1335 if (icmp_data_raw_len <
1336 (ssize_t)(oip_header_len + sizeof(struct icmp))) {
1337 if (options & F_VERBOSE)
1338 warnx("inner packet too short (%zd bytes) from %s",
1339 icmp_data_raw_len, inet_ntoa(from->sin_addr));
1340 return;
1341 }
1342
1343 memcpy(&oip, icmp_data_raw, sizeof(struct ip));
1344 oicmp_raw = icmp_data_raw + oip_header_len;
1345 memcpy(&oicmp, oicmp_raw, sizeof(struct icmp));
1346
1347 if (((options & F_VERBOSE) && uid == 0) ||
1348 (!(options & F_QUIET2) &&
1349 (oip.ip_dst.s_addr == whereto.sin_addr.s_addr) &&
1350 (oip.ip_p == IPPROTO_ICMP) &&
1351 (oicmp.icmp_type == ICMP_ECHO) &&
1352 (oicmp.icmp_id == ident))) {
1353 (void)printf("%zd bytes from %s: ", cc,
1354 pr_addr(from->sin_addr));
1355 pr_icmph(&icp, &oip, icmp_data_raw);
1356 } else
1357 return;
1358 }
1359
1360 /* Display any IP options */
1361 cp = (u_char *)buf + sizeof(struct ip);
1362
1363 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
1364 switch (*cp) {
1365 case IPOPT_EOL:
1366 hlen = 0;
1367 break;
1368 case IPOPT_LSRR:
1369 case IPOPT_SSRR:
1370 (void)printf(*cp == IPOPT_LSRR ?
1371 "\nLSRR: " : "\nSSRR: ");
1372 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
1373 hlen -= 2;
1374 cp += 2;
1375 if (j >= INADDR_LEN &&
1376 j <= hlen - (int)sizeof(struct ip)) {
1377 for (;;) {
1378 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1379 if (ina.s_addr == 0)
1380 (void)printf("\t0.0.0.0");
1381 else
1382 (void)printf("\t%s",
1383 pr_addr(ina));
1384 hlen -= INADDR_LEN;
1385 cp += INADDR_LEN - 1;
1386 j -= INADDR_LEN;
1387 if (j < INADDR_LEN)
1388 break;
1389 (void)putchar('\n');
1390 }
1391 } else
1392 (void)printf("\t(truncated route)");
1393 break;
1394 case IPOPT_RR:
1395 j = cp[IPOPT_OLEN]; /* get length */
1396 i = cp[IPOPT_OFFSET]; /* and pointer */
1397 hlen -= 2;
1398 cp += 2;
1399 if (i > j)
1400 i = j;
1401 i = i - IPOPT_MINOFF + 1;
1402 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
1403 old_rrlen = 0;
1404 continue;
1405 }
1406 if (i == old_rrlen
1407 && !bcmp((char *)cp, old_rr, i)
1408 && !(options & F_DOT)) {
1409 (void)printf("\t(same route)");
1410 hlen -= i;
1411 cp += i;
1412 break;
1413 }
1414 old_rrlen = i;
1415 bcopy((char *)cp, old_rr, i);
1416 (void)printf("\nRR: ");
1417 if (i >= INADDR_LEN &&
1418 i <= hlen - (int)sizeof(struct ip)) {
1419 for (;;) {
1420 bcopy(++cp, &ina.s_addr, INADDR_LEN);
1421 if (ina.s_addr == 0)
1422 (void)printf("\t0.0.0.0");
1423 else
1424 (void)printf("\t%s",
1425 pr_addr(ina));
1426 hlen -= INADDR_LEN;
1427 cp += INADDR_LEN - 1;
1428 i -= INADDR_LEN;
1429 if (i < INADDR_LEN)
1430 break;
1431 (void)putchar('\n');
1432 }
1433 } else
1434 (void)printf("\t(truncated route)");
1435 break;
1436 case IPOPT_NOP:
1437 (void)printf("\nNOP");
1438 break;
1439 default:
1440 (void)printf("\nunknown option %x", *cp);
1441 break;
1442 }
1443 if (!(options & F_DOT)) {
1444 (void)putchar('\n');
1445 (void)fflush(stdout);
1446 }
1447 }
1448
1449 /*
1450 * pr_icmph --
1451 * Print a descriptive string about an ICMP header.
1452 */
1453 static void
pr_icmph(struct icmp * icp,struct ip * oip,const u_char * const oicmp_raw)1454 pr_icmph(struct icmp *icp, struct ip *oip, const u_char *const oicmp_raw)
1455 {
1456
1457 switch(icp->icmp_type) {
1458 case ICMP_ECHOREPLY:
1459 (void)printf("Echo Reply\n");
1460 /* XXX ID + Seq + Data */
1461 break;
1462 case ICMP_UNREACH:
1463 switch(icp->icmp_code) {
1464 case ICMP_UNREACH_NET:
1465 (void)printf("Destination Net Unreachable\n");
1466 break;
1467 case ICMP_UNREACH_HOST:
1468 (void)printf("Destination Host Unreachable\n");
1469 break;
1470 case ICMP_UNREACH_PROTOCOL:
1471 (void)printf("Destination Protocol Unreachable\n");
1472 break;
1473 case ICMP_UNREACH_PORT:
1474 (void)printf("Destination Port Unreachable\n");
1475 break;
1476 case ICMP_UNREACH_NEEDFRAG:
1477 (void)printf("frag needed and DF set (MTU %d)\n",
1478 ntohs(icp->icmp_nextmtu));
1479 break;
1480 case ICMP_UNREACH_SRCFAIL:
1481 (void)printf("Source Route Failed\n");
1482 break;
1483 case ICMP_UNREACH_FILTER_PROHIB:
1484 (void)printf("Communication prohibited by filter\n");
1485 break;
1486 default:
1487 (void)printf("Dest Unreachable, Bad Code: %d\n",
1488 icp->icmp_code);
1489 break;
1490 }
1491 /* Print returned IP header information */
1492 pr_iph(oip, oicmp_raw);
1493 break;
1494 case ICMP_SOURCEQUENCH:
1495 (void)printf("Source Quench\n");
1496 pr_iph(oip, oicmp_raw);
1497 break;
1498 case ICMP_REDIRECT:
1499 switch(icp->icmp_code) {
1500 case ICMP_REDIRECT_NET:
1501 (void)printf("Redirect Network");
1502 break;
1503 case ICMP_REDIRECT_HOST:
1504 (void)printf("Redirect Host");
1505 break;
1506 case ICMP_REDIRECT_TOSNET:
1507 (void)printf("Redirect Type of Service and Network");
1508 break;
1509 case ICMP_REDIRECT_TOSHOST:
1510 (void)printf("Redirect Type of Service and Host");
1511 break;
1512 default:
1513 (void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1514 break;
1515 }
1516 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1517 pr_iph(oip, oicmp_raw);
1518 break;
1519 case ICMP_ECHO:
1520 (void)printf("Echo Request\n");
1521 /* XXX ID + Seq + Data */
1522 break;
1523 case ICMP_TIMXCEED:
1524 switch(icp->icmp_code) {
1525 case ICMP_TIMXCEED_INTRANS:
1526 (void)printf("Time to live exceeded\n");
1527 break;
1528 case ICMP_TIMXCEED_REASS:
1529 (void)printf("Frag reassembly time exceeded\n");
1530 break;
1531 default:
1532 (void)printf("Time exceeded, Bad Code: %d\n",
1533 icp->icmp_code);
1534 break;
1535 }
1536 pr_iph(oip, oicmp_raw);
1537 break;
1538 case ICMP_PARAMPROB:
1539 (void)printf("Parameter problem: pointer = 0x%02x\n",
1540 icp->icmp_hun.ih_pptr);
1541 pr_iph(oip, oicmp_raw);
1542 break;
1543 case ICMP_TSTAMP:
1544 (void)printf("Timestamp\n");
1545 /* XXX ID + Seq + 3 timestamps */
1546 break;
1547 case ICMP_TSTAMPREPLY:
1548 (void)printf("Timestamp Reply\n");
1549 /* XXX ID + Seq + 3 timestamps */
1550 break;
1551 case ICMP_IREQ:
1552 (void)printf("Information Request\n");
1553 /* XXX ID + Seq */
1554 break;
1555 case ICMP_IREQREPLY:
1556 (void)printf("Information Reply\n");
1557 /* XXX ID + Seq */
1558 break;
1559 case ICMP_MASKREQ:
1560 (void)printf("Address Mask Request\n");
1561 break;
1562 case ICMP_MASKREPLY:
1563 (void)printf("Address Mask Reply\n");
1564 break;
1565 case ICMP_ROUTERADVERT:
1566 (void)printf("Router Advertisement\n");
1567 break;
1568 case ICMP_ROUTERSOLICIT:
1569 (void)printf("Router Solicitation\n");
1570 break;
1571 default:
1572 (void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1573 }
1574 }
1575
1576 /*
1577 * pr_iph --
1578 * Print an IP header with options.
1579 */
1580 static void
pr_iph(struct ip * ip,const u_char * cp)1581 pr_iph(struct ip *ip, const u_char *cp)
1582 {
1583 struct in_addr dst_ina, src_ina;
1584 int hlen;
1585
1586 hlen = ip->ip_hl << 2;
1587 cp = cp + sizeof(struct ip); /* point to options */
1588
1589 memcpy(&src_ina, &ip->ip_src.s_addr, sizeof(src_ina));
1590 memcpy(&dst_ina, &ip->ip_dst.s_addr, sizeof(dst_ina));
1591
1592 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks %*s %*s",
1593 (int)strlen(inet_ntoa(src_ina)), "Src",
1594 (int)strlen(inet_ntoa(dst_ina)), "Dst");
1595 if (hlen > (int)sizeof(struct ip))
1596 (void)printf(" Opts");
1597 (void)putchar('\n');
1598 (void)printf(" %1x %1x %02x %04x %04x",
1599 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1600 ntohs(ip->ip_id));
1601 (void)printf(" %1x %04x",
1602 (ntohs(ip->ip_off) & 0xe000) >> 13,
1603 ntohs(ip->ip_off) & 0x1fff);
1604 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p,
1605 ntohs(ip->ip_sum));
1606 (void)printf(" %s", inet_ntoa(src_ina));
1607 (void)printf(" %s", inet_ntoa(dst_ina));
1608 /* dump any option bytes */
1609 if (hlen > (int)sizeof(struct ip)) {
1610 (void)printf(" ");
1611 while (hlen-- > (int)sizeof(struct ip)) {
1612 (void)printf("%02x", *cp++);
1613 }
1614 }
1615 (void)putchar('\n');
1616 }
1617
1618 /*
1619 * pr_addr --
1620 * Return an ascii host address as a dotted quad and optionally with
1621 * a hostname.
1622 */
1623 static char *
pr_addr(struct in_addr ina)1624 pr_addr(struct in_addr ina)
1625 {
1626 struct hostent *hp;
1627 static char buf[16 + 3 + MAXHOSTNAMELEN];
1628
1629 if (!(options & F_HOSTNAME))
1630 return inet_ntoa(ina);
1631
1632 hp = cap_gethostbyaddr(capdns, (char *)&ina, sizeof(ina), AF_INET);
1633
1634 if (hp == NULL)
1635 return inet_ntoa(ina);
1636
1637 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1638 inet_ntoa(ina));
1639 return(buf);
1640 }
1641
1642 static char *
pr_ntime(n_time timestamp)1643 pr_ntime(n_time timestamp)
1644 {
1645 static char buf[11];
1646 int hour, min, sec;
1647
1648 sec = ntohl(timestamp) / 1000;
1649 hour = sec / 60 / 60;
1650 min = (sec % (60 * 60)) / 60;
1651 sec = (sec % (60 * 60)) % 60;
1652
1653 (void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour, min, sec);
1654
1655 return (buf);
1656 }
1657
1658 static void
fill(char * bp,char * patp)1659 fill(char *bp, char *patp)
1660 {
1661 char *cp;
1662 int pat[16];
1663 u_int ii, jj, kk;
1664
1665 for (cp = patp; *cp; cp++) {
1666 if (!isxdigit(*cp))
1667 errx(EX_USAGE,
1668 "patterns must be specified as hex digits");
1669
1670 }
1671 ii = sscanf(patp,
1672 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1673 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1674 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1675 &pat[13], &pat[14], &pat[15]);
1676
1677 if (ii > 0)
1678 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii)
1679 for (jj = 0; jj < ii; ++jj)
1680 bp[jj + kk] = pat[jj];
1681 if (!(options & F_QUIET)) {
1682 (void)printf("PATTERN: 0x");
1683 for (jj = 0; jj < ii; ++jj)
1684 (void)printf("%02x", bp[jj] & 0xFF);
1685 (void)printf("\n");
1686 }
1687 }
1688
1689 static cap_channel_t *
capdns_setup(void)1690 capdns_setup(void)
1691 {
1692 cap_channel_t *capcas, *capdnsloc;
1693 #ifdef WITH_CASPER
1694 const char *types[2];
1695 int families[1];
1696 #endif
1697 capcas = cap_init();
1698 if (capcas == NULL)
1699 err(1, "unable to create casper process");
1700 capdnsloc = cap_service_open(capcas, "system.dns");
1701 /* Casper capability no longer needed. */
1702 cap_close(capcas);
1703 if (capdnsloc == NULL)
1704 err(1, "unable to open system.dns service");
1705 #ifdef WITH_CASPER
1706 types[0] = "NAME2ADDR";
1707 types[1] = "ADDR2NAME";
1708 if (cap_dns_type_limit(capdnsloc, types, 2) < 0)
1709 err(1, "unable to limit access to system.dns service");
1710 families[0] = AF_INET;
1711 if (cap_dns_family_limit(capdnsloc, families, 1) < 0)
1712 err(1, "unable to limit access to system.dns service");
1713 #endif
1714 return (capdnsloc);
1715 }
1716