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 ((int)sizeof(struct ip) + MAX_IPOPTLEN) 100 #define MAXPAYLOAD (IP_MAXPACKET - MAXIPLEN - ICMP_MINLEN) 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 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 packet size for ping sweep */ 317 ltmp = strtonum(optarg, 1, INT_MAX, &errstr); 318 if (errstr != NULL) { 319 errx(EX_USAGE, "invalid packet size: `%s'", 320 optarg); 321 } 322 sweepmax = (int)ltmp; 323 if (uid != 0 && sweepmax > DEFDATALEN) { 324 errc(EX_NOPERM, EPERM, 325 "packet size too large: %d > %u", 326 sweepmax, DEFDATALEN); 327 } 328 options |= F_SWEEP; 329 break; 330 case 'g': /* Minimum packet size for ping sweep */ 331 ltmp = strtonum(optarg, 1, INT_MAX, &errstr); 332 if (errstr != NULL) { 333 errx(EX_USAGE, "invalid packet size: `%s'", 334 optarg); 335 } 336 sweepmin = (int)ltmp; 337 if (uid != 0 && sweepmin > DEFDATALEN) { 338 errc(EX_NOPERM, EPERM, 339 "packet 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': /* Packet size increment for ping sweep */ 348 ltmp = strtonum(optarg, 1, INT_MAX, &errstr); 349 if (errstr != NULL) { 350 errx(EX_USAGE, "invalid packet size: `%s'", 351 optarg); 352 } 353 sweepincr = (int)ltmp; 354 if (uid != 0 && sweepincr > DEFDATALEN) { 355 errc(EX_NOPERM, EPERM, 356 "packet 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 (datalen > MAXPAYLOAD) { 462 errx(EX_USAGE, 463 "packet size too large: %d > %u", 464 datalen, MAXPAYLOAD); 465 } 466 break; 467 case 'T': /* multicast TTL */ 468 ltmp = strtonum(optarg, 0, MAXTTL, &errstr); 469 if (errstr != NULL) 470 errx(EX_USAGE, "invalid multicast TTL: `%s'", 471 optarg); 472 mttl = (unsigned char)ltmp; 473 options |= F_MTTL; 474 break; 475 case 't': 476 alarmtimeout = strtoul(optarg, &ep, 0); 477 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX)) 478 errx(EX_USAGE, "invalid timeout: `%s'", 479 optarg); 480 if (alarmtimeout > MAXALARM) 481 errx(EX_USAGE, "invalid timeout: `%s' > %d", 482 optarg, MAXALARM); 483 { 484 struct itimerval itv; 485 486 timerclear(&itv.it_interval); 487 timerclear(&itv.it_value); 488 itv.it_value.tv_sec = (time_t)alarmtimeout; 489 if (setitimer(ITIMER_REAL, &itv, NULL) != 0) 490 err(1, "setitimer"); 491 } 492 break; 493 case 'v': 494 options |= F_VERBOSE; 495 break; 496 case 'W': /* wait ms for answer */ 497 t = strtod(optarg, &ep); 498 if (*ep || ep == optarg || t > (double)INT_MAX) 499 errx(EX_USAGE, "invalid timing interval: `%s'", 500 optarg); 501 options |= F_WAITTIME; 502 waittime = (int)t; 503 break; 504 case 'z': 505 options |= F_HDRINCL; 506 ltmp = strtol(optarg, &ep, 0); 507 if (*ep || ep == optarg || ltmp > MAXTOS || ltmp < 0) 508 errx(EX_USAGE, "invalid TOS: `%s'", optarg); 509 tos = ltmp; 510 break; 511 default: 512 usage(); 513 } 514 } 515 516 if (argc - optind != 1) 517 usage(); 518 target = argv[optind]; 519 520 switch (options & (F_MASK|F_TIME)) { 521 case 0: break; 522 case F_MASK: 523 icmp_type = ICMP_MASKREQ; 524 icmp_type_rsp = ICMP_MASKREPLY; 525 phdr_len = MASK_LEN; 526 if (!(options & F_QUIET)) 527 (void)printf("ICMP_MASKREQ\n"); 528 break; 529 case F_TIME: 530 icmp_type = ICMP_TSTAMP; 531 icmp_type_rsp = ICMP_TSTAMPREPLY; 532 phdr_len = TS_LEN; 533 if (!(options & F_QUIET)) 534 (void)printf("ICMP_TSTAMP\n"); 535 break; 536 default: 537 errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive."); 538 break; 539 } 540 icmp_len = sizeof(struct ip) + ICMP_MINLEN + phdr_len; 541 if (options & F_RROUTE) 542 icmp_len += MAX_IPOPTLEN; 543 maxpayload = IP_MAXPACKET - icmp_len; 544 if (datalen > maxpayload) 545 errx(EX_USAGE, "packet size too large: %d > %d", datalen, 546 maxpayload); 547 send_len = icmp_len + datalen; 548 datap = &outpack[ICMP_MINLEN + phdr_len + TIMEVAL_LEN]; 549 if (options & F_PINGFILLED) { 550 fill((char *)datap, payload); 551 } 552 capdns = capdns_setup(); 553 if (source) { 554 bzero((char *)&sock_in, sizeof(sock_in)); 555 sock_in.sin_family = AF_INET; 556 if (inet_aton(source, &sock_in.sin_addr) != 0) { 557 shostname = source; 558 } else { 559 hp = cap_gethostbyname2(capdns, source, AF_INET); 560 if (!hp) 561 errx(EX_NOHOST, "cannot resolve %s: %s", 562 source, hstrerror(h_errno)); 563 564 sock_in.sin_len = sizeof sock_in; 565 if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) || 566 hp->h_length < 0) 567 errx(1, "gethostbyname2: illegal address"); 568 memcpy(&sock_in.sin_addr, hp->h_addr_list[0], 569 sizeof(sock_in.sin_addr)); 570 (void)strncpy(snamebuf, hp->h_name, 571 sizeof(snamebuf) - 1); 572 snamebuf[sizeof(snamebuf) - 1] = '\0'; 573 shostname = snamebuf; 574 } 575 if (bind(ssend, (struct sockaddr *)&sock_in, sizeof sock_in) == 576 -1) 577 err(1, "bind"); 578 } 579 580 bzero(&whereto, sizeof(whereto)); 581 to = &whereto; 582 to->sin_family = AF_INET; 583 to->sin_len = sizeof *to; 584 if (inet_aton(target, &to->sin_addr) != 0) { 585 hostname = target; 586 } else { 587 hp = cap_gethostbyname2(capdns, target, AF_INET); 588 if (!hp) 589 errx(EX_NOHOST, "cannot resolve %s: %s", 590 target, hstrerror(h_errno)); 591 592 if ((unsigned)hp->h_length > sizeof(to->sin_addr)) 593 errx(1, "gethostbyname2 returned an illegal address"); 594 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr); 595 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1); 596 hnamebuf[sizeof(hnamebuf) - 1] = '\0'; 597 hostname = hnamebuf; 598 } 599 600 /* From now on we will use only reverse DNS lookups. */ 601 #ifdef WITH_CASPER 602 if (capdns != NULL) { 603 const char *types[1]; 604 605 types[0] = "ADDR2NAME"; 606 if (cap_dns_type_limit(capdns, types, 1) < 0) 607 err(1, "unable to limit access to system.dns service"); 608 } 609 #endif 610 if (connect(ssend, (struct sockaddr *)&whereto, sizeof(whereto)) != 0) 611 err(1, "connect"); 612 613 if (options & F_FLOOD && options & F_INTERVAL) 614 errx(EX_USAGE, "-f and -i: incompatible options"); 615 616 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 617 errx(EX_USAGE, 618 "-f flag cannot be used with multicast destination"); 619 if (options & (F_MIF | F_NOLOOP | F_MTTL) 620 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 621 errx(EX_USAGE, 622 "-I, -L, -T flags cannot be used with unicast destination"); 623 624 if (datalen >= TIMEVAL_LEN) /* can we time transfer */ 625 timing = 1; 626 627 if ((options & (F_PINGFILLED | F_SWEEP)) == 0) 628 for (i = TIMEVAL_LEN; i < datalen; ++i) 629 *datap++ = i; 630 631 ident = getpid() & 0xFFFF; 632 633 hold = 1; 634 if (options & F_SO_DEBUG) { 635 (void)setsockopt(ssend, SOL_SOCKET, SO_DEBUG, (char *)&hold, 636 sizeof(hold)); 637 (void)setsockopt(srecv, SOL_SOCKET, SO_DEBUG, (char *)&hold, 638 sizeof(hold)); 639 } 640 if (options & F_SO_DONTROUTE) 641 (void)setsockopt(ssend, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, 642 sizeof(hold)); 643 if (options & F_IP_VLAN_PCP) { 644 (void)setsockopt(ssend, IPPROTO_IP, IP_VLAN_PCP, (char *)&pcp, 645 sizeof(pcp)); 646 } 647 #ifdef IPSEC 648 #ifdef IPSEC_POLICY_IPSEC 649 if (options & F_POLICY) { 650 char *buf; 651 if (policy_in != NULL) { 652 buf = ipsec_set_policy(policy_in, strlen(policy_in)); 653 if (buf == NULL) 654 errx(EX_CONFIG, "%s", ipsec_strerror()); 655 if (setsockopt(srecv, IPPROTO_IP, IP_IPSEC_POLICY, 656 buf, ipsec_get_policylen(buf)) < 0) 657 err(EX_CONFIG, 658 "ipsec policy cannot be configured"); 659 free(buf); 660 } 661 662 if (policy_out != NULL) { 663 buf = ipsec_set_policy(policy_out, strlen(policy_out)); 664 if (buf == NULL) 665 errx(EX_CONFIG, "%s", ipsec_strerror()); 666 if (setsockopt(ssend, IPPROTO_IP, IP_IPSEC_POLICY, 667 buf, ipsec_get_policylen(buf)) < 0) 668 err(EX_CONFIG, 669 "ipsec policy cannot be configured"); 670 free(buf); 671 } 672 } 673 #endif /*IPSEC_POLICY_IPSEC*/ 674 #endif /*IPSEC*/ 675 676 if (options & F_HDRINCL) { 677 struct ip ip; 678 679 memcpy(&ip, outpackhdr, sizeof(ip)); 680 if (!(options & (F_TTL | F_MTTL))) { 681 mib[0] = CTL_NET; 682 mib[1] = PF_INET; 683 mib[2] = IPPROTO_IP; 684 mib[3] = IPCTL_DEFTTL; 685 sz = sizeof(ttl); 686 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1) 687 err(1, "sysctl(net.inet.ip.ttl)"); 688 } 689 setsockopt(ssend, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold)); 690 ip.ip_v = IPVERSION; 691 ip.ip_hl = sizeof(struct ip) >> 2; 692 ip.ip_tos = tos; 693 ip.ip_id = 0; 694 ip.ip_off = htons(df ? IP_DF : 0); 695 ip.ip_ttl = ttl; 696 ip.ip_p = IPPROTO_ICMP; 697 ip.ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY; 698 ip.ip_dst = to->sin_addr; 699 memcpy(outpackhdr, &ip, sizeof(ip)); 700 } 701 702 /* 703 * Here we enter capability mode. Further down access to global 704 * namespaces (e.g filesystem) is restricted (see capsicum(4)). 705 * We must connect(2) our socket before this point. 706 */ 707 caph_cache_catpages(); 708 if (caph_enter_casper() < 0) 709 err(1, "caph_enter_casper"); 710 711 cap_rights_init(&rights, CAP_RECV, CAP_EVENT, CAP_SETSOCKOPT); 712 if (caph_rights_limit(srecv, &rights) < 0) 713 err(1, "cap_rights_limit srecv"); 714 cap_rights_init(&rights, CAP_SEND, CAP_SETSOCKOPT); 715 if (caph_rights_limit(ssend, &rights) < 0) 716 err(1, "cap_rights_limit ssend"); 717 718 /* record route option */ 719 if (options & F_RROUTE) { 720 #ifdef IP_OPTIONS 721 bzero(rspace, sizeof(rspace)); 722 rspace[IPOPT_OPTVAL] = IPOPT_RR; 723 rspace[IPOPT_OLEN] = sizeof(rspace) - 1; 724 rspace[IPOPT_OFFSET] = IPOPT_MINOFF; 725 rspace[sizeof(rspace) - 1] = IPOPT_EOL; 726 if (setsockopt(ssend, IPPROTO_IP, IP_OPTIONS, rspace, 727 sizeof(rspace)) < 0) 728 err(EX_OSERR, "setsockopt IP_OPTIONS"); 729 #else 730 errx(EX_UNAVAILABLE, 731 "record route not available in this implementation"); 732 #endif /* IP_OPTIONS */ 733 } 734 735 if (options & F_TTL) { 736 if (setsockopt(ssend, IPPROTO_IP, IP_TTL, &ttl, 737 sizeof(ttl)) < 0) { 738 err(EX_OSERR, "setsockopt IP_TTL"); 739 } 740 } 741 if (options & F_NOLOOP) { 742 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, 743 sizeof(loop)) < 0) { 744 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP"); 745 } 746 } 747 if (options & F_MTTL) { 748 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, 749 sizeof(mttl)) < 0) { 750 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL"); 751 } 752 } 753 if (options & F_MIF) { 754 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, 755 sizeof(ifaddr)) < 0) { 756 err(EX_OSERR, "setsockopt IP_MULTICAST_IF"); 757 } 758 } 759 #ifdef SO_TIMESTAMP 760 { 761 int on = 1; 762 int ts_clock = SO_TS_MONOTONIC; 763 if (setsockopt(srecv, SOL_SOCKET, SO_TIMESTAMP, &on, 764 sizeof(on)) < 0) 765 err(EX_OSERR, "setsockopt SO_TIMESTAMP"); 766 if (setsockopt(srecv, SOL_SOCKET, SO_TS_CLOCK, &ts_clock, 767 sizeof(ts_clock)) < 0) 768 err(EX_OSERR, "setsockopt SO_TS_CLOCK"); 769 } 770 #endif 771 if (sweepmax) { 772 if (sweepmin > sweepmax) 773 errx(EX_USAGE, 774 "Maximum packet size must be no less than the minimum packet size"); 775 776 if (sweepmax > maxpayload - TIMEVAL_LEN) 777 errx(EX_USAGE, "Invalid sweep maximum"); 778 779 if (datalen != DEFDATALEN) 780 errx(EX_USAGE, 781 "Packet size and ping sweep are mutually exclusive"); 782 783 if (npackets > 0) { 784 snpackets = npackets; 785 npackets = 0; 786 } else 787 snpackets = 1; 788 datalen = sweepmin; 789 send_len = icmp_len + sweepmin; 790 } 791 if (options & F_SWEEP && !sweepmax) 792 errx(EX_USAGE, "Maximum sweep size must be specified"); 793 794 /* 795 * When pinging the broadcast address, you can get a lot of answers. 796 * Doing something so evil is useful if you are trying to stress the 797 * ethernet, or just want to fill the arp cache to get some stuff for 798 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast 799 * or multicast pings if they wish. 800 */ 801 802 /* 803 * XXX receive buffer needs undetermined space for mbuf overhead 804 * as well. 805 */ 806 hold = IP_MAXPACKET + 128; 807 (void)setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, (char *)&hold, 808 sizeof(hold)); 809 /* CAP_SETSOCKOPT removed */ 810 cap_rights_init(&rights, CAP_RECV, CAP_EVENT); 811 if (caph_rights_limit(srecv, &rights) < 0) 812 err(1, "cap_rights_limit srecv setsockopt"); 813 if (uid == 0) 814 (void)setsockopt(ssend, SOL_SOCKET, SO_SNDBUF, (char *)&hold, 815 sizeof(hold)); 816 /* CAP_SETSOCKOPT removed */ 817 cap_rights_init(&rights, CAP_SEND); 818 if (caph_rights_limit(ssend, &rights) < 0) 819 err(1, "cap_rights_limit ssend setsockopt"); 820 821 if (to->sin_family == AF_INET) { 822 (void)printf("PING %s (%s)", hostname, 823 inet_ntoa(to->sin_addr)); 824 if (source) 825 (void)printf(" from %s", shostname); 826 if (sweepmax) 827 (void)printf(": (%d ... %d) data bytes\n", 828 sweepmin, sweepmax); 829 else 830 (void)printf(": %d data bytes\n", datalen); 831 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 840 /* 841 * Use sigaction() instead of signal() to get unambiguous semantics, 842 * in particular with SA_RESTART not set. 843 */ 844 845 sigemptyset(&si_sa.sa_mask); 846 si_sa.sa_flags = 0; 847 si_sa.sa_handler = onsignal; 848 if (sigaction(SIGINT, &si_sa, 0) == -1) 849 err(EX_OSERR, "sigaction SIGINT"); 850 seenint = 0; 851 if (sigaction(SIGINFO, &si_sa, 0) == -1) 852 err(EX_OSERR, "sigaction SIGINFO"); 853 seeninfo = 0; 854 if (alarmtimeout > 0) { 855 if (sigaction(SIGALRM, &si_sa, 0) == -1) 856 err(EX_OSERR, "sigaction SIGALRM"); 857 } 858 859 bzero(&msg, sizeof(msg)); 860 msg.msg_name = (caddr_t)&from; 861 msg.msg_iov = &iov; 862 msg.msg_iovlen = 1; 863 #ifdef SO_TIMESTAMP 864 msg.msg_control = (caddr_t)ctrl; 865 msg.msg_controllen = sizeof(ctrl); 866 #endif 867 iov.iov_base = packet; 868 iov.iov_len = IP_MAXPACKET; 869 870 if (preload == 0) 871 pinger(); /* send the first ping */ 872 else { 873 if (npackets != 0 && preload > npackets) 874 preload = npackets; 875 while (preload--) /* fire off them quickies */ 876 pinger(); 877 } 878 (void)clock_gettime(CLOCK_MONOTONIC, &last); 879 880 if (options & F_FLOOD) { 881 intvl.tv_sec = 0; 882 intvl.tv_nsec = 10000000; 883 } else { 884 intvl.tv_sec = interval / 1000; 885 intvl.tv_nsec = interval % 1000 * 1000000; 886 } 887 888 almost_done = 0; 889 while (seenint == 0) { 890 struct timespec now, timeout; 891 fd_set rfds; 892 int n; 893 ssize_t cc; 894 895 /* signal handling */ 896 if (seeninfo) { 897 pr_summary(stderr); 898 seeninfo = 0; 899 continue; 900 } 901 if ((unsigned)srecv >= FD_SETSIZE) 902 errx(EX_OSERR, "descriptor too large"); 903 FD_ZERO(&rfds); 904 FD_SET(srecv, &rfds); 905 (void)clock_gettime(CLOCK_MONOTONIC, &now); 906 timespecadd(&last, &intvl, &timeout); 907 timespecsub(&timeout, &now, &timeout); 908 if (timeout.tv_sec < 0) 909 timespecclear(&timeout); 910 911 n = pselect(srecv + 1, &rfds, NULL, NULL, &timeout, NULL); 912 if (n < 0) 913 continue; /* EINTR */ 914 if (n == 1) { 915 struct timespec *tv = NULL; 916 #ifdef SO_TIMESTAMP 917 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); 918 #endif 919 msg.msg_namelen = sizeof(from); 920 if ((cc = recvmsg(srecv, &msg, 0)) < 0) { 921 if (errno == EINTR) 922 continue; 923 warn("recvmsg"); 924 continue; 925 } 926 /* If we have a 0 byte read from recvfrom continue */ 927 if (cc == 0) 928 continue; 929 #ifdef SO_TIMESTAMP 930 if (cmsg != NULL && 931 cmsg->cmsg_level == SOL_SOCKET && 932 cmsg->cmsg_type == SCM_TIMESTAMP && 933 cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) { 934 /* Copy to avoid alignment problems: */ 935 memcpy(&now, CMSG_DATA(cmsg), sizeof(now)); 936 tv = &now; 937 } 938 #endif 939 if (tv == NULL) { 940 (void)clock_gettime(CLOCK_MONOTONIC, &now); 941 tv = &now; 942 } 943 pr_pack((char *)packet, cc, &from, tv); 944 if ((options & F_ONCE && nreceived) || 945 (npackets && nreceived >= npackets)) 946 break; 947 } 948 if (n == 0 || (options & F_FLOOD)) { 949 if (sweepmax && sntransmitted == snpackets) { 950 if (datalen + sweepincr > sweepmax) 951 break; 952 for (i = 0; i < sweepincr; i++) 953 *datap++ = i; 954 datalen += sweepincr; 955 send_len = icmp_len + datalen; 956 sntransmitted = 0; 957 } 958 if (!npackets || ntransmitted < npackets) 959 pinger(); 960 else { 961 if (almost_done) 962 break; 963 almost_done = 1; 964 /* 965 * If we're not transmitting any more packets, 966 * change the timer to wait two round-trip times 967 * if we've received any packets or (waittime) 968 * milliseconds if we haven't. 969 */ 970 intvl.tv_nsec = 0; 971 if (nreceived) { 972 intvl.tv_sec = 2 * tmax / 1000; 973 if (intvl.tv_sec == 0) 974 intvl.tv_sec = 1; 975 } else { 976 intvl.tv_sec = waittime / 1000; 977 intvl.tv_nsec = 978 waittime % 1000 * 1000000; 979 } 980 } 981 (void)clock_gettime(CLOCK_MONOTONIC, &last); 982 if (ntransmitted - nreceived - 1 > nmissedmax) { 983 nmissedmax = ntransmitted - nreceived - 1; 984 if (options & F_MISSED) 985 (void)write(STDOUT_FILENO, &BBELL, 1); 986 } 987 } 988 } 989 pr_summary(stdout); 990 991 exit(nreceived ? 0 : 2); 992 } 993 994 /* 995 * pinger -- 996 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet 997 * will be added on by the kernel. The ID field is our UNIX process ID, 998 * and the sequence number is an ascending integer. The first TIMEVAL_LEN 999 * bytes of the data portion are used to hold a UNIX "timespec" struct in 1000 * host byte-order, to compute the round-trip time. 1001 */ 1002 static void 1003 pinger(void) 1004 { 1005 struct timespec now; 1006 struct tv32 tv32; 1007 struct icmp icp; 1008 int cc, i; 1009 u_char *packet; 1010 1011 packet = outpack; 1012 memcpy(&icp, outpack, ICMP_MINLEN + phdr_len); 1013 icp.icmp_type = icmp_type; 1014 icp.icmp_code = 0; 1015 icp.icmp_cksum = 0; 1016 icp.icmp_seq = htons(ntransmitted); 1017 icp.icmp_id = ident; /* ID */ 1018 1019 CLR(ntransmitted % mx_dup_ck); 1020 1021 if ((options & F_TIME) || timing) { 1022 (void)clock_gettime(CLOCK_MONOTONIC, &now); 1023 /* 1024 * Truncate seconds down to 32 bits in order 1025 * to fit the timestamp within 8 bytes of the 1026 * packet. We're only concerned with 1027 * durations, not absolute times. 1028 */ 1029 tv32.tv32_sec = (uint32_t)htonl(now.tv_sec); 1030 tv32.tv32_nsec = (uint32_t)htonl(now.tv_nsec); 1031 if (options & F_TIME) 1032 icp.icmp_otime = htonl((now.tv_sec % (24*60*60)) 1033 * 1000 + now.tv_nsec / 1000000); 1034 if (timing) 1035 bcopy((void *)&tv32, 1036 (void *)&outpack[ICMP_MINLEN + phdr_len], 1037 sizeof(tv32)); 1038 } 1039 1040 memcpy(outpack, &icp, ICMP_MINLEN + phdr_len); 1041 1042 cc = ICMP_MINLEN + phdr_len + datalen; 1043 1044 /* compute ICMP checksum here */ 1045 icp.icmp_cksum = in_cksum(outpack, cc); 1046 /* Update icmp_cksum in the raw packet data buffer. */ 1047 memcpy(outpack + offsetof(struct icmp, icmp_cksum), &icp.icmp_cksum, 1048 sizeof(icp.icmp_cksum)); 1049 1050 if (options & F_HDRINCL) { 1051 struct ip ip; 1052 1053 cc += sizeof(struct ip); 1054 ip.ip_len = htons(cc); 1055 /* Update ip_len in the raw packet data buffer. */ 1056 memcpy(outpackhdr + offsetof(struct ip, ip_len), &ip.ip_len, 1057 sizeof(ip.ip_len)); 1058 ip.ip_sum = in_cksum(outpackhdr, cc); 1059 /* Update ip_sum in the raw packet data buffer. */ 1060 memcpy(outpackhdr + offsetof(struct ip, ip_sum), &ip.ip_sum, 1061 sizeof(ip.ip_sum)); 1062 packet = outpackhdr; 1063 } 1064 i = send(ssend, (char *)packet, cc, 0); 1065 if (i < 0 || i != cc) { 1066 if (i < 0) { 1067 if (options & F_FLOOD && errno == ENOBUFS) { 1068 usleep(FLOOD_BACKOFF); 1069 return; 1070 } 1071 warn("sendto"); 1072 } else { 1073 warn("%s: partial write: %d of %d bytes", 1074 hostname, i, cc); 1075 } 1076 } 1077 ntransmitted++; 1078 sntransmitted++; 1079 if (!(options & F_QUIET) && options & F_DOT) 1080 (void)write(STDOUT_FILENO, &DOT[DOTidx++ % DOTlen], 1); 1081 } 1082 1083 /* 1084 * pr_pack -- 1085 * Print out the packet, if it came from us. This logic is necessary 1086 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets 1087 * which arrive ('tis only fair). This permits multiple copies of this 1088 * program to be run without having intermingled output (or statistics!). 1089 */ 1090 static void 1091 pr_pack(char *buf, ssize_t cc, struct sockaddr_in *from, struct timespec *tv) 1092 { 1093 struct in_addr ina; 1094 u_char *cp, *dp, l; 1095 struct icmp icp; 1096 struct ip ip; 1097 const u_char *icmp_data_raw; 1098 ssize_t icmp_data_raw_len; 1099 double triptime; 1100 int dupflag, i, j, recv_len; 1101 int8_t hlen; 1102 uint16_t seq; 1103 static int old_rrlen; 1104 static char old_rr[MAX_IPOPTLEN]; 1105 struct ip oip; 1106 u_char oip_header_len; 1107 struct icmp oicmp; 1108 const u_char *oicmp_raw; 1109 1110 /* 1111 * Get size of IP header of the received packet. 1112 * The header length is contained in the lower four bits of the first 1113 * byte and represents the number of 4 byte octets the header takes up. 1114 * 1115 * The IHL minimum value is 5 (20 bytes) and its maximum value is 15 1116 * (60 bytes). 1117 */ 1118 memcpy(&l, buf, sizeof(l)); 1119 hlen = (l & 0x0f) << 2; 1120 1121 /* Reject IP packets with a short header */ 1122 if (hlen < (int8_t) sizeof(struct ip)) { 1123 if (options & F_VERBOSE) 1124 warn("IHL too short (%d bytes) from %s", hlen, 1125 inet_ntoa(from->sin_addr)); 1126 return; 1127 } 1128 1129 memcpy(&ip, buf, sizeof(struct ip)); 1130 1131 /* Check packet has enough data to carry a valid ICMP header */ 1132 recv_len = cc; 1133 if (cc < hlen + ICMP_MINLEN) { 1134 if (options & F_VERBOSE) 1135 warn("packet too short (%zd bytes) from %s", cc, 1136 inet_ntoa(from->sin_addr)); 1137 return; 1138 } 1139 1140 icmp_data_raw_len = cc - (hlen + offsetof(struct icmp, icmp_data)); 1141 icmp_data_raw = buf + hlen + offsetof(struct icmp, icmp_data); 1142 1143 /* Now the ICMP part */ 1144 cc -= hlen; 1145 memcpy(&icp, buf + hlen, MIN((ssize_t)sizeof(icp), cc)); 1146 if (icp.icmp_type == icmp_type_rsp) { 1147 if (icp.icmp_id != ident) 1148 return; /* 'Twas not our ECHO */ 1149 ++nreceived; 1150 triptime = 0.0; 1151 if (timing) { 1152 struct timespec tv1; 1153 struct tv32 tv32; 1154 const u_char *tp; 1155 1156 tp = icmp_data_raw + phdr_len; 1157 1158 if ((size_t)(cc - ICMP_MINLEN - phdr_len) >= 1159 sizeof(tv1)) { 1160 /* Copy to avoid alignment problems: */ 1161 memcpy(&tv32, tp, sizeof(tv32)); 1162 tv1.tv_sec = ntohl(tv32.tv32_sec); 1163 tv1.tv_nsec = ntohl(tv32.tv32_nsec); 1164 timespecsub(tv, &tv1, tv); 1165 triptime = ((double)tv->tv_sec) * 1000.0 + 1166 ((double)tv->tv_nsec) / 1000000.0; 1167 if (triptime < 0) { 1168 warnx("time of day goes back (%.3f ms)," 1169 " clamping time to 0", 1170 triptime); 1171 triptime = 0; 1172 } 1173 tsum += triptime; 1174 tsumsq += triptime * triptime; 1175 if (triptime < tmin) 1176 tmin = triptime; 1177 if (triptime > tmax) 1178 tmax = triptime; 1179 } else 1180 timing = 0; 1181 } 1182 1183 seq = ntohs(icp.icmp_seq); 1184 1185 if (TST(seq % mx_dup_ck)) { 1186 ++nrepeats; 1187 --nreceived; 1188 dupflag = 1; 1189 } else { 1190 SET(seq % mx_dup_ck); 1191 dupflag = 0; 1192 } 1193 1194 if (options & F_QUIET) 1195 return; 1196 1197 if (options & F_WAITTIME && triptime > waittime) { 1198 ++nrcvtimeout; 1199 return; 1200 } 1201 1202 if (options & F_DOT) 1203 (void)write(STDOUT_FILENO, &BSPACE, 1); 1204 else { 1205 (void)printf("%zd bytes from %s: icmp_seq=%u", cc, 1206 pr_addr(from->sin_addr), seq); 1207 (void)printf(" ttl=%d", ip.ip_ttl); 1208 if (timing) 1209 (void)printf(" time=%.3f ms", triptime); 1210 if (dupflag) 1211 (void)printf(" (DUP!)"); 1212 if (options & F_AUDIBLE) 1213 (void)write(STDOUT_FILENO, &BBELL, 1); 1214 if (options & F_MASK) { 1215 /* Just prentend this cast isn't ugly */ 1216 (void)printf(" mask=%s", 1217 inet_ntoa(*(struct in_addr *)&(icp.icmp_mask))); 1218 } 1219 if (options & F_TIME) { 1220 (void)printf(" tso=%s", pr_ntime(icp.icmp_otime)); 1221 (void)printf(" tsr=%s", pr_ntime(icp.icmp_rtime)); 1222 (void)printf(" tst=%s", pr_ntime(icp.icmp_ttime)); 1223 } 1224 if (recv_len != send_len) { 1225 (void)printf( 1226 "\nwrong total length %d instead of %d", 1227 recv_len, send_len); 1228 } 1229 /* check the data */ 1230 cp = (u_char*)(buf + hlen + offsetof(struct icmp, 1231 icmp_data) + phdr_len); 1232 dp = &outpack[ICMP_MINLEN + phdr_len]; 1233 cc -= ICMP_MINLEN + phdr_len; 1234 i = 0; 1235 if (timing) { /* don't check variable timestamp */ 1236 cp += TIMEVAL_LEN; 1237 dp += TIMEVAL_LEN; 1238 cc -= TIMEVAL_LEN; 1239 i += TIMEVAL_LEN; 1240 } 1241 for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) { 1242 if (*cp != *dp) { 1243 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", 1244 i, *dp, *cp); 1245 (void)printf("\ncp:"); 1246 cp = (u_char*)(buf + hlen + 1247 offsetof(struct icmp, icmp_data)); 1248 for (i = 0; i < datalen; ++i, ++cp) { 1249 if ((i % 16) == 8) 1250 (void)printf("\n\t"); 1251 (void)printf(" %2x", *cp); 1252 } 1253 (void)printf("\ndp:"); 1254 cp = &outpack[ICMP_MINLEN]; 1255 for (i = 0; i < datalen; ++i, ++cp) { 1256 if ((i % 16) == 8) 1257 (void)printf("\n\t"); 1258 (void)printf(" %2x", *cp); 1259 } 1260 break; 1261 } 1262 } 1263 } 1264 } else { 1265 /* 1266 * We've got something other than an ECHOREPLY. 1267 * See if it's a reply to something that we sent. 1268 * We can compare IP destination, protocol, 1269 * and ICMP type and ID. 1270 * 1271 * Only print all the error messages if we are running 1272 * as root to avoid leaking information not normally 1273 * available to those not running as root. 1274 */ 1275 1276 /* 1277 * If we don't have enough bytes for a quoted IP header and an 1278 * ICMP header then stop. 1279 */ 1280 if (icmp_data_raw_len < 1281 (ssize_t)(sizeof(struct ip) + sizeof(struct icmp))) { 1282 if (options & F_VERBOSE) 1283 warnx("quoted data too short (%zd bytes) from %s", 1284 icmp_data_raw_len, inet_ntoa(from->sin_addr)); 1285 return; 1286 } 1287 1288 memcpy(&oip_header_len, icmp_data_raw, sizeof(oip_header_len)); 1289 oip_header_len = (oip_header_len & 0x0f) << 2; 1290 1291 /* Reject IP packets with a short header */ 1292 if (oip_header_len < sizeof(struct ip)) { 1293 if (options & F_VERBOSE) 1294 warnx("inner IHL too short (%d bytes) from %s", 1295 oip_header_len, inet_ntoa(from->sin_addr)); 1296 return; 1297 } 1298 1299 /* 1300 * Check against the actual IHL length, to protect against 1301 * quoated packets carrying IP options. 1302 */ 1303 if (icmp_data_raw_len < 1304 (ssize_t)(oip_header_len + sizeof(struct icmp))) { 1305 if (options & F_VERBOSE) 1306 warnx("inner packet too short (%zd bytes) from %s", 1307 icmp_data_raw_len, inet_ntoa(from->sin_addr)); 1308 return; 1309 } 1310 1311 memcpy(&oip, icmp_data_raw, sizeof(struct ip)); 1312 oicmp_raw = icmp_data_raw + oip_header_len; 1313 memcpy(&oicmp, oicmp_raw, sizeof(struct icmp)); 1314 1315 if (((options & F_VERBOSE) && uid == 0) || 1316 (!(options & F_QUIET2) && 1317 (oip.ip_dst.s_addr == whereto.sin_addr.s_addr) && 1318 (oip.ip_p == IPPROTO_ICMP) && 1319 (oicmp.icmp_type == ICMP_ECHO) && 1320 (oicmp.icmp_id == ident))) { 1321 (void)printf("%zd bytes from %s: ", cc, 1322 pr_addr(from->sin_addr)); 1323 pr_icmph(&icp, &oip, icmp_data_raw); 1324 } else 1325 return; 1326 } 1327 1328 /* Display any IP options */ 1329 cp = (u_char *)buf + sizeof(struct ip); 1330 1331 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp) 1332 switch (*cp) { 1333 case IPOPT_EOL: 1334 hlen = 0; 1335 break; 1336 case IPOPT_LSRR: 1337 case IPOPT_SSRR: 1338 (void)printf(*cp == IPOPT_LSRR ? 1339 "\nLSRR: " : "\nSSRR: "); 1340 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1; 1341 hlen -= 2; 1342 cp += 2; 1343 if (j >= INADDR_LEN && 1344 j <= hlen - (int)sizeof(struct ip)) { 1345 for (;;) { 1346 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1347 if (ina.s_addr == 0) 1348 (void)printf("\t0.0.0.0"); 1349 else 1350 (void)printf("\t%s", 1351 pr_addr(ina)); 1352 hlen -= INADDR_LEN; 1353 cp += INADDR_LEN - 1; 1354 j -= INADDR_LEN; 1355 if (j < INADDR_LEN) 1356 break; 1357 (void)putchar('\n'); 1358 } 1359 } else 1360 (void)printf("\t(truncated route)"); 1361 break; 1362 case IPOPT_RR: 1363 j = cp[IPOPT_OLEN]; /* get length */ 1364 i = cp[IPOPT_OFFSET]; /* and pointer */ 1365 hlen -= 2; 1366 cp += 2; 1367 if (i > j) 1368 i = j; 1369 i = i - IPOPT_MINOFF + 1; 1370 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) { 1371 old_rrlen = 0; 1372 continue; 1373 } 1374 if (i == old_rrlen 1375 && !bcmp((char *)cp, old_rr, i) 1376 && !(options & F_DOT)) { 1377 (void)printf("\t(same route)"); 1378 hlen -= i; 1379 cp += i; 1380 break; 1381 } 1382 old_rrlen = i; 1383 bcopy((char *)cp, old_rr, i); 1384 (void)printf("\nRR: "); 1385 if (i >= INADDR_LEN && 1386 i <= hlen - (int)sizeof(struct ip)) { 1387 for (;;) { 1388 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1389 if (ina.s_addr == 0) 1390 (void)printf("\t0.0.0.0"); 1391 else 1392 (void)printf("\t%s", 1393 pr_addr(ina)); 1394 hlen -= INADDR_LEN; 1395 cp += INADDR_LEN - 1; 1396 i -= INADDR_LEN; 1397 if (i < INADDR_LEN) 1398 break; 1399 (void)putchar('\n'); 1400 } 1401 } else 1402 (void)printf("\t(truncated route)"); 1403 break; 1404 case IPOPT_NOP: 1405 (void)printf("\nNOP"); 1406 break; 1407 default: 1408 (void)printf("\nunknown option %x", *cp); 1409 break; 1410 } 1411 if (!(options & F_DOT)) { 1412 (void)putchar('\n'); 1413 (void)fflush(stdout); 1414 } 1415 } 1416 1417 /* 1418 * pr_icmph -- 1419 * Print a descriptive string about an ICMP header. 1420 */ 1421 static void 1422 pr_icmph(struct icmp *icp, struct ip *oip, const u_char *const oicmp_raw) 1423 { 1424 1425 switch(icp->icmp_type) { 1426 case ICMP_ECHOREPLY: 1427 (void)printf("Echo Reply\n"); 1428 /* XXX ID + Seq + Data */ 1429 break; 1430 case ICMP_UNREACH: 1431 switch(icp->icmp_code) { 1432 case ICMP_UNREACH_NET: 1433 (void)printf("Destination Net Unreachable\n"); 1434 break; 1435 case ICMP_UNREACH_HOST: 1436 (void)printf("Destination Host Unreachable\n"); 1437 break; 1438 case ICMP_UNREACH_PROTOCOL: 1439 (void)printf("Destination Protocol Unreachable\n"); 1440 break; 1441 case ICMP_UNREACH_PORT: 1442 (void)printf("Destination Port Unreachable\n"); 1443 break; 1444 case ICMP_UNREACH_NEEDFRAG: 1445 (void)printf("frag needed and DF set (MTU %d)\n", 1446 ntohs(icp->icmp_nextmtu)); 1447 break; 1448 case ICMP_UNREACH_SRCFAIL: 1449 (void)printf("Source Route Failed\n"); 1450 break; 1451 case ICMP_UNREACH_FILTER_PROHIB: 1452 (void)printf("Communication prohibited by filter\n"); 1453 break; 1454 default: 1455 (void)printf("Dest Unreachable, Bad Code: %d\n", 1456 icp->icmp_code); 1457 break; 1458 } 1459 /* Print returned IP header information */ 1460 pr_iph(oip, oicmp_raw); 1461 break; 1462 case ICMP_SOURCEQUENCH: 1463 (void)printf("Source Quench\n"); 1464 pr_iph(oip, oicmp_raw); 1465 break; 1466 case ICMP_REDIRECT: 1467 switch(icp->icmp_code) { 1468 case ICMP_REDIRECT_NET: 1469 (void)printf("Redirect Network"); 1470 break; 1471 case ICMP_REDIRECT_HOST: 1472 (void)printf("Redirect Host"); 1473 break; 1474 case ICMP_REDIRECT_TOSNET: 1475 (void)printf("Redirect Type of Service and Network"); 1476 break; 1477 case ICMP_REDIRECT_TOSHOST: 1478 (void)printf("Redirect Type of Service and Host"); 1479 break; 1480 default: 1481 (void)printf("Redirect, Bad Code: %d", icp->icmp_code); 1482 break; 1483 } 1484 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr)); 1485 pr_iph(oip, oicmp_raw); 1486 break; 1487 case ICMP_ECHO: 1488 (void)printf("Echo Request\n"); 1489 /* XXX ID + Seq + Data */ 1490 break; 1491 case ICMP_TIMXCEED: 1492 switch(icp->icmp_code) { 1493 case ICMP_TIMXCEED_INTRANS: 1494 (void)printf("Time to live exceeded\n"); 1495 break; 1496 case ICMP_TIMXCEED_REASS: 1497 (void)printf("Frag reassembly time exceeded\n"); 1498 break; 1499 default: 1500 (void)printf("Time exceeded, Bad Code: %d\n", 1501 icp->icmp_code); 1502 break; 1503 } 1504 pr_iph(oip, oicmp_raw); 1505 break; 1506 case ICMP_PARAMPROB: 1507 (void)printf("Parameter problem: pointer = 0x%02x\n", 1508 icp->icmp_hun.ih_pptr); 1509 pr_iph(oip, oicmp_raw); 1510 break; 1511 case ICMP_TSTAMP: 1512 (void)printf("Timestamp\n"); 1513 /* XXX ID + Seq + 3 timestamps */ 1514 break; 1515 case ICMP_TSTAMPREPLY: 1516 (void)printf("Timestamp Reply\n"); 1517 /* XXX ID + Seq + 3 timestamps */ 1518 break; 1519 case ICMP_IREQ: 1520 (void)printf("Information Request\n"); 1521 /* XXX ID + Seq */ 1522 break; 1523 case ICMP_IREQREPLY: 1524 (void)printf("Information Reply\n"); 1525 /* XXX ID + Seq */ 1526 break; 1527 case ICMP_MASKREQ: 1528 (void)printf("Address Mask Request\n"); 1529 break; 1530 case ICMP_MASKREPLY: 1531 (void)printf("Address Mask Reply\n"); 1532 break; 1533 case ICMP_ROUTERADVERT: 1534 (void)printf("Router Advertisement\n"); 1535 break; 1536 case ICMP_ROUTERSOLICIT: 1537 (void)printf("Router Solicitation\n"); 1538 break; 1539 default: 1540 (void)printf("Bad ICMP type: %d\n", icp->icmp_type); 1541 } 1542 } 1543 1544 /* 1545 * pr_iph -- 1546 * Print an IP header with options. 1547 */ 1548 static void 1549 pr_iph(struct ip *ip, const u_char *cp) 1550 { 1551 struct in_addr dst_ina, src_ina; 1552 int hlen; 1553 1554 hlen = ip->ip_hl << 2; 1555 cp = cp + sizeof(struct ip); /* point to options */ 1556 1557 memcpy(&src_ina, &ip->ip_src.s_addr, sizeof(src_ina)); 1558 memcpy(&dst_ina, &ip->ip_dst.s_addr, sizeof(dst_ina)); 1559 1560 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks %*s %*s", 1561 (int)strlen(inet_ntoa(src_ina)), "Src", 1562 (int)strlen(inet_ntoa(dst_ina)), "Dst"); 1563 if (hlen > (int)sizeof(struct ip)) 1564 (void)printf(" Opts"); 1565 (void)putchar('\n'); 1566 (void)printf(" %1x %1x %02x %04x %04x", 1567 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len), 1568 ntohs(ip->ip_id)); 1569 (void)printf(" %1x %04x", 1570 (ntohs(ip->ip_off) & 0xe000) >> 13, 1571 ntohs(ip->ip_off) & 0x1fff); 1572 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, 1573 ntohs(ip->ip_sum)); 1574 (void)printf(" %s", inet_ntoa(src_ina)); 1575 (void)printf(" %s", inet_ntoa(dst_ina)); 1576 /* dump any option bytes */ 1577 if (hlen > (int)sizeof(struct ip)) { 1578 (void)printf(" "); 1579 while (hlen-- > (int)sizeof(struct ip)) { 1580 (void)printf("%02x", *cp++); 1581 } 1582 } 1583 (void)putchar('\n'); 1584 } 1585 1586 /* 1587 * pr_addr -- 1588 * Return an ascii host address as a dotted quad and optionally with 1589 * a hostname. 1590 */ 1591 static char * 1592 pr_addr(struct in_addr ina) 1593 { 1594 struct hostent *hp; 1595 static char buf[16 + 3 + MAXHOSTNAMELEN]; 1596 1597 if (!(options & F_HOSTNAME)) 1598 return inet_ntoa(ina); 1599 1600 hp = cap_gethostbyaddr(capdns, (char *)&ina, sizeof(ina), AF_INET); 1601 1602 if (hp == NULL) 1603 return inet_ntoa(ina); 1604 1605 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1606 inet_ntoa(ina)); 1607 return(buf); 1608 } 1609 1610 static char * 1611 pr_ntime(n_time timestamp) 1612 { 1613 static char buf[11]; 1614 int hour, min, sec; 1615 1616 sec = ntohl(timestamp) / 1000; 1617 hour = sec / 60 / 60; 1618 min = (sec % (60 * 60)) / 60; 1619 sec = (sec % (60 * 60)) % 60; 1620 1621 (void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour, min, sec); 1622 1623 return (buf); 1624 } 1625 1626 static void 1627 fill(char *bp, char *patp) 1628 { 1629 char *cp; 1630 int pat[16]; 1631 u_int ii, jj, kk; 1632 1633 for (cp = patp; *cp; cp++) { 1634 if (!isxdigit(*cp)) 1635 errx(EX_USAGE, 1636 "patterns must be specified as hex digits"); 1637 1638 } 1639 ii = sscanf(patp, 1640 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1641 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], 1642 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], 1643 &pat[13], &pat[14], &pat[15]); 1644 1645 if (ii > 0) 1646 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii) 1647 for (jj = 0; jj < ii; ++jj) 1648 bp[jj + kk] = pat[jj]; 1649 if (!(options & F_QUIET)) { 1650 (void)printf("PATTERN: 0x"); 1651 for (jj = 0; jj < ii; ++jj) 1652 (void)printf("%02x", bp[jj] & 0xFF); 1653 (void)printf("\n"); 1654 } 1655 } 1656 1657 static cap_channel_t * 1658 capdns_setup(void) 1659 { 1660 cap_channel_t *capcas, *capdnsloc; 1661 #ifdef WITH_CASPER 1662 const char *types[2]; 1663 int families[1]; 1664 #endif 1665 capcas = cap_init(); 1666 if (capcas == NULL) 1667 err(1, "unable to create casper process"); 1668 capdnsloc = cap_service_open(capcas, "system.dns"); 1669 /* Casper capability no longer needed. */ 1670 cap_close(capcas); 1671 if (capdnsloc == NULL) 1672 err(1, "unable to open system.dns service"); 1673 #ifdef WITH_CASPER 1674 types[0] = "NAME2ADDR"; 1675 types[1] = "ADDR2NAME"; 1676 if (cap_dns_type_limit(capdnsloc, types, 2) < 0) 1677 err(1, "unable to limit access to system.dns service"); 1678 families[0] = AF_INET; 1679 if (cap_dns_family_limit(capdnsloc, families, 1) < 0) 1680 err(1, "unable to limit access to system.dns service"); 1681 #endif 1682 return (capdnsloc); 1683 } 1684