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