1 /* $NetBSD: pflogd.c,v 1.8 2010/12/13 01:45:38 christos Exp $ */ 2 /* $OpenBSD: pflogd.c,v 1.45 2007/06/06 14:11:26 henning Exp $ */ 3 4 /* 5 * Copyright (c) 2001 Theo de Raadt 6 * Copyright (c) 2001 Can Erkin Acar 7 * All rights reserved. 8 * 9 * Redistribution and use in source and binary forms, with or without 10 * modification, are permitted provided that the following conditions 11 * are met: 12 * 13 * - Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * - Redistributions in binary form must reproduce the above 16 * copyright notice, this list of conditions and the following 17 * disclaimer in the documentation and/or other materials provided 18 * with the distribution. 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 28 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 30 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 31 * POSSIBILITY OF SUCH DAMAGE. 32 */ 33 34 #include <sys/types.h> 35 #include <sys/ioctl.h> 36 #include <sys/file.h> 37 #include <sys/stat.h> 38 #include <sys/socket.h> 39 #include <net/if.h> 40 #include <stdio.h> 41 #include <stdlib.h> 42 #include <string.h> 43 #include <unistd.h> 44 /* 45 * If we're going to include parts of the libpcap internals we MUST 46 * set the feature-test macros they expect, or they may misbehave. 47 */ 48 #define HAVE_STRLCPY 49 #define HAVE_SNPRINTF 50 #define HAVE_VSNPRINTF 51 #include <pcap-int.h> 52 #include <pcap.h> 53 #include <syslog.h> 54 #include <signal.h> 55 #include <err.h> 56 #include <errno.h> 57 #include <stdarg.h> 58 #include <fcntl.h> 59 #include <util.h> 60 #include "pflogd.h" 61 62 pcap_t *hpcap; 63 static FILE *dpcap; 64 65 int Debug = 0; 66 static uint32_t snaplen = DEF_SNAPLEN; 67 static uint32_t cur_snaplen = DEF_SNAPLEN; 68 69 volatile sig_atomic_t gotsig_close, gotsig_alrm, gotsig_hup; 70 71 const char *filename = PFLOGD_LOG_FILE; 72 const char *interface = PFLOGD_DEFAULT_IF; 73 const char *filter = NULL; 74 75 char errbuf[PCAP_ERRBUF_SIZE]; 76 77 int log_debug = 0; 78 unsigned int delay = FLUSH_DELAY; 79 80 char *copy_argv(char * const *); 81 void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *); 82 void dump_packet_nobuf(u_char *, const struct pcap_pkthdr *, const u_char *); 83 int flush_buffer(FILE *); 84 int if_exists(const char *); 85 int init_pcap(void); 86 void logmsg(int, const char *, ...); 87 void purge_buffer(void); 88 int reset_dump(int); 89 int scan_dump(FILE *, off_t); 90 int set_snaplen(uint32_t); 91 void set_suspended(int); 92 void sig_alrm(int); 93 void sig_close(int); 94 void sig_hup(int); 95 void usage(void); 96 97 static int try_reset_dump(int); 98 99 /* buffer must always be greater than snaplen */ 100 static size_t bufpkt = 0; /* number of packets in buffer */ 101 static size_t buflen = 0; /* allocated size of buffer */ 102 static char *buffer = NULL; /* packet buffer */ 103 static char *bufpos = NULL; /* position in buffer */ 104 static size_t bufleft = 0; /* bytes left in buffer */ 105 106 /* if error, stop logging but count dropped packets */ 107 static int suspended = -1; 108 static long packets_dropped = 0; 109 110 void 111 set_suspended(int s) 112 { 113 if (suspended == s) 114 return; 115 116 suspended = s; 117 setproctitle("[%s] -s %d -i %s -f %s", 118 suspended ? "suspended" : "running", 119 cur_snaplen, interface, filename); 120 } 121 122 char * 123 copy_argv(char * const *argv) 124 { 125 size_t len = 0, n; 126 char *buf; 127 128 if (argv == NULL) 129 return (NULL); 130 131 for (n = 0; argv[n]; n++) 132 len += strlen(argv[n])+1; 133 if (len == 0) 134 return (NULL); 135 136 buf = malloc(len); 137 if (buf == NULL) 138 return (NULL); 139 140 strlcpy(buf, argv[0], len); 141 for (n = 1; argv[n]; n++) { 142 strlcat(buf, " ", len); 143 strlcat(buf, argv[n], len); 144 } 145 return (buf); 146 } 147 148 void 149 logmsg(int pri, const char *message, ...) 150 { 151 va_list ap; 152 va_start(ap, message); 153 154 if (log_debug) { 155 vfprintf(stderr, message, ap); 156 fprintf(stderr, "\n"); 157 } else 158 vsyslog(pri, message, ap); 159 va_end(ap); 160 } 161 162 __dead void 163 usage(void) 164 { 165 fprintf(stderr, "usage: pflogd [-Dx] [-d delay] [-f filename]"); 166 fprintf(stderr, " [-i interface] [-p pidfile]\n"); 167 fprintf(stderr, " [-s snaplen] [expression]\n"); 168 exit(1); 169 } 170 171 void 172 sig_close(int sig) 173 { 174 gotsig_close = 1; 175 } 176 177 void 178 sig_hup(int sig) 179 { 180 gotsig_hup = 1; 181 } 182 183 void 184 sig_alrm(int sig) 185 { 186 gotsig_alrm = 1; 187 } 188 189 void 190 set_pcap_filter(void) 191 { 192 struct bpf_program bprog; 193 194 if (pcap_compile(hpcap, &bprog, filter, PCAP_OPT_FIL, 0) < 0) 195 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap)); 196 else { 197 if (pcap_setfilter(hpcap, &bprog) < 0) 198 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap)); 199 pcap_freecode(&bprog); 200 } 201 } 202 203 int 204 if_exists(const char *ifname) 205 { 206 int s; 207 #ifdef SIOCGIFDATA 208 struct ifdatareq ifr; 209 #define ifr_name ifdr_name 210 #else 211 struct ifreq ifr; 212 struct if_data ifrdat; 213 #endif 214 215 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 216 err(1, "socket"); 217 bzero(&ifr, sizeof(ifr)); 218 if (strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)) >= 219 sizeof(ifr.ifr_name)) 220 errx(1, "main ifr_name: strlcpy"); 221 #ifndef ifr_name 222 ifr.ifr_data = (caddr_t)&ifrdat; 223 #endif 224 if (ioctl(s, SIOCGIFDATA, (caddr_t)&ifr) == -1) 225 return (0); 226 if (close(s)) 227 err(1, "close"); 228 229 return (1); 230 } 231 232 int 233 init_pcap(void) 234 { 235 hpcap = pcap_open_live(interface, snaplen, 1, PCAP_TO_MS, errbuf); 236 if (hpcap == NULL) { 237 logmsg(LOG_ERR, "Failed to initialize: %s", errbuf); 238 return (-1); 239 } 240 241 if (pcap_datalink(hpcap) != DLT_PFLOG) { 242 logmsg(LOG_ERR, "Invalid datalink type"); 243 pcap_close(hpcap); 244 hpcap = NULL; 245 return (-1); 246 } 247 248 set_pcap_filter(); 249 250 cur_snaplen = snaplen = pcap_snapshot(hpcap); 251 252 /* lock */ 253 #ifdef __OpenBSD__ 254 if (ioctl(pcap_fileno(hpcap), BIOCLOCK) < 0) { 255 logmsg(LOG_ERR, "BIOCLOCK: %s", strerror(errno)); 256 return (-1); 257 } 258 #endif 259 260 return (0); 261 } 262 263 int 264 set_snaplen(uint32_t snap) 265 { 266 if (priv_set_snaplen(snap)) 267 return (1); 268 269 if (cur_snaplen > snap) 270 purge_buffer(); 271 272 cur_snaplen = snap; 273 274 return (0); 275 } 276 277 int 278 reset_dump(int nomove) 279 { 280 int ret; 281 282 for (;;) { 283 ret = try_reset_dump(nomove); 284 if (ret <= 0) 285 break; 286 } 287 288 return (ret); 289 } 290 291 /* 292 * tries to (re)open log file, nomove flag is used with -x switch 293 * returns 0: success, 1: retry (log moved), -1: error 294 */ 295 int 296 try_reset_dump(int nomove) 297 { 298 struct pcap_file_header hdr; 299 struct stat st; 300 int fd; 301 FILE *fp; 302 303 if (hpcap == NULL) 304 return (-1); 305 306 if (dpcap) { 307 flush_buffer(dpcap); 308 fclose(dpcap); 309 dpcap = NULL; 310 } 311 312 /* 313 * Basically reimplement pcap_dump_open() because it truncates 314 * files and duplicates headers and such. 315 */ 316 fd = priv_open_log(); 317 if (fd < 0) 318 return (-1); 319 320 fp = fdopen(fd, "a+"); 321 322 if (fp == NULL) { 323 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno)); 324 close(fd); 325 return (-1); 326 } 327 if (fstat(fileno(fp), &st) == -1) { 328 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno)); 329 fclose(fp); 330 return (-1); 331 } 332 333 /* set FILE unbuffered, we do our own buffering */ 334 if (setvbuf(fp, NULL, _IONBF, 0)) { 335 logmsg(LOG_ERR, "Failed to set output buffers"); 336 fclose(fp); 337 return (-1); 338 } 339 340 #define TCPDUMP_MAGIC 0xa1b2c3d4 341 342 if (st.st_size == 0) { 343 if (snaplen != cur_snaplen) { 344 logmsg(LOG_NOTICE, "Using snaplen %d", snaplen); 345 if (set_snaplen(snaplen)) 346 logmsg(LOG_WARNING, 347 "Failed, using old settings"); 348 } 349 hdr.magic = TCPDUMP_MAGIC; 350 hdr.version_major = PCAP_VERSION_MAJOR; 351 hdr.version_minor = PCAP_VERSION_MINOR; 352 hdr.thiszone = hpcap->tzoff; 353 hdr.snaplen = hpcap->snapshot; 354 hdr.sigfigs = 0; 355 hdr.linktype = hpcap->linktype; 356 357 if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1) { 358 fclose(fp); 359 return (-1); 360 } 361 } else if (scan_dump(fp, st.st_size)) { 362 fclose(fp); 363 if (nomove || priv_move_log()) { 364 logmsg(LOG_ERR, 365 "Invalid/incompatible log file, move it away"); 366 return (-1); 367 } 368 return (1); 369 } 370 371 dpcap = fp; 372 373 set_suspended(0); 374 flush_buffer(fp); 375 376 return (0); 377 } 378 379 int 380 scan_dump(FILE *fp, off_t size) 381 { 382 struct pcap_file_header hdr; 383 #ifdef __OpenBSD__ 384 struct pcap_pkthdr ph; 385 #else 386 struct pcap_sf_pkthdr ph; 387 #endif 388 off_t pos; 389 390 /* 391 * Must read the file, compare the header against our new 392 * options (in particular, snaplen) and adjust our options so 393 * that we generate a correct file. Furthermore, check the file 394 * for consistency so that we can append safely. 395 * 396 * XXX this may take a long time for large logs. 397 */ 398 (void) fseek(fp, 0L, SEEK_SET); 399 400 if (fread((char *)&hdr, sizeof(hdr), 1, fp) != 1) { 401 logmsg(LOG_ERR, "Short file header"); 402 return (1); 403 } 404 405 if (hdr.magic != TCPDUMP_MAGIC || 406 hdr.version_major != PCAP_VERSION_MAJOR || 407 hdr.version_minor != PCAP_VERSION_MINOR || 408 hdr.linktype != (uint32_t)hpcap->linktype || 409 hdr.snaplen > PFLOGD_MAXSNAPLEN) { 410 return (1); 411 } 412 413 pos = sizeof(hdr); 414 415 while (!feof(fp)) { 416 off_t len = fread((char *)&ph, 1, sizeof(ph), fp); 417 if (len == 0) 418 break; 419 420 if (len != sizeof(ph)) 421 goto error; 422 if (ph.caplen > hdr.snaplen || ph.caplen > PFLOGD_MAXSNAPLEN) 423 goto error; 424 pos += sizeof(ph) + ph.caplen; 425 if (pos > size) 426 goto error; 427 fseek(fp, ph.caplen, SEEK_CUR); 428 } 429 430 if (pos != size) 431 goto error; 432 433 if (hdr.snaplen != cur_snaplen) { 434 logmsg(LOG_WARNING, 435 "Existing file has different snaplen %u, using it", 436 hdr.snaplen); 437 if (set_snaplen(hdr.snaplen)) { 438 logmsg(LOG_WARNING, 439 "Failed, using old settings, offset %llu", 440 (unsigned long long) size); 441 } 442 } 443 444 return (0); 445 446 error: 447 logmsg(LOG_ERR, "Corrupted log file."); 448 return (1); 449 } 450 451 /* dump a packet directly to the stream, which is unbuffered */ 452 void 453 dump_packet_nobuf(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) 454 { 455 #ifndef __OpenBSD__ 456 struct pcap_sf_pkthdr sf_hdr; 457 #endif 458 FILE *f = (FILE *)user; 459 460 if (suspended) { 461 packets_dropped++; 462 return; 463 } 464 465 #ifndef __OpenBSD__ 466 sf_hdr.ts.tv_sec = h->ts.tv_sec; 467 sf_hdr.ts.tv_usec = h->ts.tv_usec; 468 sf_hdr.caplen = h->caplen; 469 sf_hdr.len = h->len; 470 #endif 471 472 #ifdef __OpenBSD__ 473 if (fwrite((char *)h, sizeof(*h), 1, f) != 1) { 474 #else 475 if (fwrite(&sf_hdr, sizeof(sf_hdr), 1, f) != 1) { 476 #endif 477 /* try to undo header to prevent corruption */ 478 size_t pos = (size_t)ftello(f); 479 #ifdef __OpenBSD__ 480 if (pos < sizeof(*h) || 481 ftruncate(fileno(f), pos - sizeof(*h))) { 482 #else 483 if (pos < sizeof(sf_hdr) || 484 ftruncate(fileno(f), pos - sizeof(sf_hdr))) { 485 #endif 486 logmsg(LOG_ERR, "Write failed, corrupted logfile!"); 487 set_suspended(1); 488 gotsig_close = 1; 489 return; 490 } 491 goto error; 492 } 493 494 if (fwrite(sp, h->caplen, 1, f) != 1) 495 goto error; 496 497 return; 498 499 error: 500 set_suspended(1); 501 packets_dropped ++; 502 logmsg(LOG_ERR, "Logging suspended: fwrite: %s", strerror(errno)); 503 } 504 505 int 506 flush_buffer(FILE *f) 507 { 508 off_t offset; 509 int len = bufpos - buffer; 510 511 if (len <= 0) 512 return (0); 513 514 offset = ftello(f); 515 if (offset == (off_t)-1) { 516 set_suspended(1); 517 logmsg(LOG_ERR, "Logging suspended: ftello: %s", 518 strerror(errno)); 519 return (1); 520 } 521 522 if (fwrite(buffer, len, 1, f) != 1) { 523 set_suspended(1); 524 logmsg(LOG_ERR, "Logging suspended: fwrite: %s", 525 strerror(errno)); 526 ftruncate(fileno(f), offset); 527 return (1); 528 } 529 530 set_suspended(0); 531 bufpos = buffer; 532 bufleft = buflen; 533 bufpkt = 0; 534 535 return (0); 536 } 537 538 void 539 purge_buffer(void) 540 { 541 packets_dropped += bufpkt; 542 543 set_suspended(0); 544 bufpos = buffer; 545 bufleft = buflen; 546 bufpkt = 0; 547 } 548 549 /* append packet to the buffer, flushing if necessary */ 550 void 551 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) 552 { 553 FILE *f = (FILE *)user; 554 #ifdef __OpenBSD__ 555 size_t len = sizeof(*h) + h->caplen; 556 #else 557 struct pcap_sf_pkthdr sf_hdr; 558 size_t len = sizeof(sf_hdr) + h->caplen; 559 #endif 560 561 if (len < sizeof(*h) || h->caplen > (size_t)cur_snaplen) { 562 logmsg(LOG_NOTICE, "invalid size %u (%u/%u), packet dropped", 563 len, cur_snaplen, snaplen); 564 packets_dropped++; 565 return; 566 } 567 568 if (len <= bufleft) 569 goto append; 570 571 if (suspended) { 572 packets_dropped++; 573 return; 574 } 575 576 if (flush_buffer(f)) { 577 packets_dropped++; 578 return; 579 } 580 581 if (len > bufleft) { 582 dump_packet_nobuf(user, h, sp); 583 return; 584 } 585 586 append: 587 #ifdef __OpenBSD__ 588 memcpy(bufpos, h, sizeof(*h)); 589 memcpy(bufpos + sizeof(*h), sp, h->caplen); 590 #else 591 sf_hdr.ts.tv_sec = h->ts.tv_sec; 592 sf_hdr.ts.tv_usec = h->ts.tv_usec; 593 sf_hdr.caplen = h->caplen; 594 sf_hdr.len = h->len; 595 596 memcpy(bufpos, &sf_hdr, sizeof(sf_hdr)); 597 memcpy(bufpos + sizeof(sf_hdr), sp, h->caplen); 598 #endif 599 600 bufpos += len; 601 bufleft -= len; 602 bufpkt++; 603 604 return; 605 } 606 607 int 608 main(int argc, char **argv) 609 { 610 struct pcap_stat pstat; 611 int ch, np, ret, Xflag = 0; 612 pcap_handler phandler = dump_packet; 613 const char *errstr = NULL; 614 char *pidf = NULL; 615 616 ret = 0; 617 618 closefrom(STDERR_FILENO + 1); 619 620 while ((ch = getopt(argc, argv, "Dxd:f:i:p:s:")) != -1) { 621 switch (ch) { 622 case 'D': 623 Debug = 1; 624 break; 625 case 'd': 626 delay = strtonum(optarg, 5, 60*60, &errstr); 627 if (errstr) 628 usage(); 629 break; 630 case 'f': 631 filename = optarg; 632 break; 633 case 'i': 634 interface = optarg; 635 break; 636 case 'p': 637 pidf = optarg; 638 break; 639 case 's': 640 snaplen = strtonum(optarg, 0, PFLOGD_MAXSNAPLEN, 641 &errstr); 642 if (snaplen <= 0) 643 snaplen = DEF_SNAPLEN; 644 if (errstr) 645 snaplen = PFLOGD_MAXSNAPLEN; 646 break; 647 case 'x': 648 Xflag++; 649 break; 650 default: 651 usage(); 652 } 653 654 } 655 656 log_debug = Debug; 657 argc -= optind; 658 argv += optind; 659 660 /* does interface exist */ 661 if (!if_exists(interface)) { 662 warn("Failed to initialize: %s", interface); 663 logmsg(LOG_ERR, "Failed to initialize: %s", interface); 664 logmsg(LOG_ERR, "Exiting, init failure"); 665 exit(1); 666 } 667 668 if (!Debug) { 669 openlog("pflogd", LOG_PID | LOG_CONS, LOG_DAEMON); 670 if (daemon(0, 0)) { 671 logmsg(LOG_WARNING, "Failed to become daemon: %s", 672 strerror(errno)); 673 } 674 pidfile(pidf); 675 } 676 677 tzset(); 678 (void)umask(S_IRWXG | S_IRWXO); 679 680 /* filter will be used by the privileged process */ 681 if (argc) { 682 filter = copy_argv(argv); 683 if (filter == NULL) 684 logmsg(LOG_NOTICE, "Failed to form filter expression"); 685 } 686 687 /* initialize pcap before dropping privileges */ 688 if (init_pcap()) { 689 logmsg(LOG_ERR, "Exiting, init failure"); 690 exit(1); 691 } 692 693 /* Privilege separation begins here */ 694 if (priv_init()) { 695 logmsg(LOG_ERR, "unable to privsep"); 696 exit(1); 697 } 698 699 setproctitle("[initializing]"); 700 /* Process is now unprivileged and inside a chroot */ 701 signal(SIGTERM, sig_close); 702 signal(SIGINT, sig_close); 703 signal(SIGQUIT, sig_close); 704 signal(SIGALRM, sig_alrm); 705 signal(SIGHUP, sig_hup); 706 alarm(delay); 707 708 buffer = malloc(PFLOGD_BUFSIZE); 709 710 if (buffer == NULL) { 711 logmsg(LOG_WARNING, "Failed to allocate output buffer"); 712 phandler = dump_packet_nobuf; 713 } else { 714 bufleft = buflen = PFLOGD_BUFSIZE; 715 bufpos = buffer; 716 bufpkt = 0; 717 } 718 719 if (reset_dump(Xflag) < 0) { 720 if (Xflag) 721 return (1); 722 723 logmsg(LOG_ERR, "Logging suspended: open error"); 724 set_suspended(1); 725 } else if (Xflag) 726 return (0); 727 728 while (1) { 729 np = pcap_dispatch(hpcap, PCAP_NUM_PKTS, 730 phandler, (u_char *)dpcap); 731 if (np < 0) { 732 if (!if_exists(interface) == -1) { 733 logmsg(LOG_NOTICE, "interface %s went away", 734 interface); 735 ret = -1; 736 break; 737 } 738 logmsg(LOG_NOTICE, "%s", pcap_geterr(hpcap)); 739 } 740 741 if (gotsig_close) 742 break; 743 if (gotsig_hup) { 744 if (reset_dump(0)) { 745 logmsg(LOG_ERR, 746 "Logging suspended: open error"); 747 set_suspended(1); 748 } 749 gotsig_hup = 0; 750 } 751 752 if (gotsig_alrm) { 753 if (dpcap) 754 flush_buffer(dpcap); 755 else 756 gotsig_hup = 1; 757 gotsig_alrm = 0; 758 alarm(delay); 759 } 760 } 761 762 logmsg(LOG_NOTICE, "Exiting"); 763 if (dpcap) { 764 flush_buffer(dpcap); 765 fclose(dpcap); 766 } 767 purge_buffer(); 768 769 if (pcap_stats(hpcap, &pstat) < 0) 770 logmsg(LOG_WARNING, "Reading stats: %s", pcap_geterr(hpcap)); 771 else 772 logmsg(LOG_NOTICE, 773 "%u packets received, %u/%u dropped (kernel/pflogd)", 774 pstat.ps_recv, pstat.ps_drop, packets_dropped); 775 776 pcap_close(hpcap); 777 if (!Debug) 778 closelog(); 779 return (ret); 780 } 781