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