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