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 <machine/inttypes.h> 41 42 #include <errno.h> 43 #include <err.h> 44 #include <fcntl.h> 45 #include <syslog.h> 46 #include <signal.h> 47 #include <stdarg.h> 48 #include <stdio.h> 49 #include <stdlib.h> 50 #include <string.h> 51 #include <unistd.h> 52 53 #include <libutil.h> 54 #include <pcap-int.h> 55 #include <pcap.h> 56 57 #include "pflogd.h" 58 59 pcap_t *hpcap; 60 static FILE *dpcap; 61 62 int Debug = 0; 63 static int snaplen = DEF_SNAPLEN; 64 static int cur_snaplen = DEF_SNAPLEN; 65 66 volatile sig_atomic_t gotsig_close, gotsig_alrm, gotsig_hup; 67 68 const char *filename = PFLOGD_LOG_FILE; 69 const char *interface = PFLOGD_DEFAULT_IF; 70 char *filter = NULL; 71 72 char errbuf[PCAP_ERRBUF_SIZE]; 73 74 int log_debug = 0; 75 unsigned int delay = FLUSH_DELAY; 76 77 char *copy_argv(char * const *); 78 void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *); 79 void dump_packet_nobuf(u_char *, const struct pcap_pkthdr *, const u_char *); 80 int flush_buffer(FILE *); 81 int if_exists(char *); 82 int init_pcap(void); 83 void purge_buffer(void); 84 int reset_dump(int); 85 int scan_dump(FILE *, off_t); 86 int set_snaplen(int); 87 void set_suspended(int); 88 void sig_alrm(int); 89 void sig_close(int); 90 void sig_hup(int); 91 void usage(void); 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 set_pcap_filter(void) 187 { 188 struct bpf_program bprog; 189 190 if (pcap_compile(hpcap, &bprog, filter, PCAP_OPT_FIL, 0) < 0) 191 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap)); 192 else { 193 if (pcap_setfilter(hpcap, &bprog) < 0) 194 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap)); 195 pcap_freecode(&bprog); 196 } 197 } 198 199 int 200 if_exists(char *ifname) 201 { 202 int s; 203 struct ifreq ifr; 204 struct if_data ifrdat; 205 206 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 207 err(1, "socket"); 208 bzero(&ifr, sizeof(ifr)); 209 if (strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)) >= 210 sizeof(ifr.ifr_name)) 211 errx(1, "main ifr_name: strlcpy"); 212 ifr.ifr_data = (caddr_t)&ifrdat; 213 if (ioctl(s, SIOCGIFDATA, (caddr_t)&ifr) == -1) 214 return (0); 215 if (close(s)) 216 err(1, "close"); 217 218 return (1); 219 } 220 221 int 222 init_pcap(void) 223 { 224 hpcap = pcap_open_live(interface, snaplen, 1, PCAP_TO_MS, errbuf); 225 if (hpcap == NULL) { 226 logmsg(LOG_ERR, "Failed to initialize: %s", errbuf); 227 return (-1); 228 } 229 230 if (pcap_datalink(hpcap) != DLT_PFLOG) { 231 logmsg(LOG_ERR, "Invalid datalink type"); 232 pcap_close(hpcap); 233 hpcap = NULL; 234 return (-1); 235 } 236 237 set_pcap_filter(); 238 239 cur_snaplen = snaplen = pcap_snapshot(hpcap); 240 241 /* From contrib/pf/pflogd.c 1.5 FreeBSD: BPF locking is not 242 * (yet) supported. 243 */ 244 #ifndef __DragonFly__ 245 /* lock */ 246 if (ioctl(pcap_fileno(hpcap), BIOCLOCK) < 0) { 247 logmsg(LOG_ERR, "BIOCLOCK: %s", strerror(errno)); 248 return (-1); 249 } 250 #endif 251 252 return (0); 253 } 254 255 int 256 set_snaplen(int snap) 257 { 258 if (priv_set_snaplen(snap)) 259 return (1); 260 261 if (cur_snaplen > snap) 262 purge_buffer(); 263 264 cur_snaplen = snap; 265 266 return (0); 267 } 268 269 int 270 reset_dump(int nomove) 271 { 272 int ret; 273 274 for (;;) { 275 ret = try_reset_dump(nomove); 276 if (ret <= 0) 277 break; 278 } 279 280 return (ret); 281 } 282 283 /* 284 * tries to (re)open log file, nomove flag is used with -x switch 285 * returns 0: success, 1: retry (log moved), -1: error 286 */ 287 int 288 try_reset_dump(int nomove) 289 { 290 struct pcap_file_header hdr; 291 struct stat st; 292 int fd; 293 FILE *fp; 294 295 if (hpcap == NULL) 296 return (-1); 297 298 if (dpcap) { 299 flush_buffer(dpcap); 300 fclose(dpcap); 301 dpcap = NULL; 302 } 303 304 /* 305 * Basically reimplement pcap_dump_open() because it truncates 306 * files and duplicates headers and such. 307 */ 308 fd = priv_open_log(); 309 if (fd < 0) 310 return (-1); 311 312 fp = fdopen(fd, "a+"); 313 314 if (fp == NULL) { 315 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno)); 316 close(fd); 317 return (-1); 318 } 319 if (fstat(fileno(fp), &st) == -1) { 320 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno)); 321 fclose(fp); 322 return (-1); 323 } 324 325 /* set FILE unbuffered, we do our own buffering */ 326 if (setvbuf(fp, NULL, _IONBF, 0)) { 327 logmsg(LOG_ERR, "Failed to set output buffers"); 328 fclose(fp); 329 return (-1); 330 } 331 332 #define TCPDUMP_MAGIC 0xa1b2c3d4 333 334 if (st.st_size == 0) { 335 if (snaplen != cur_snaplen) { 336 logmsg(LOG_NOTICE, "Using snaplen %d", snaplen); 337 if (set_snaplen(snaplen)) 338 logmsg(LOG_WARNING, 339 "Failed, using old settings"); 340 } 341 hdr.magic = TCPDUMP_MAGIC; 342 hdr.version_major = PCAP_VERSION_MAJOR; 343 hdr.version_minor = PCAP_VERSION_MINOR; 344 hdr.thiszone = hpcap->tzoff; 345 hdr.snaplen = hpcap->snapshot; 346 hdr.sigfigs = 0; 347 hdr.linktype = hpcap->linktype; 348 349 if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1) { 350 fclose(fp); 351 return (-1); 352 } 353 } else if (scan_dump(fp, st.st_size)) { 354 fclose(fp); 355 if (nomove || priv_move_log()) { 356 logmsg(LOG_ERR, 357 "Invalid/incompatible log file, move it away"); 358 return (-1); 359 } 360 return (1); 361 } 362 363 dpcap = fp; 364 365 set_suspended(0); 366 flush_buffer(fp); 367 368 return (0); 369 } 370 371 int 372 scan_dump(FILE *fp, off_t size) 373 { 374 struct pcap_file_header hdr; 375 struct pcap_pkthdr ph; 376 off_t pos; 377 378 /* 379 * Must read the file, compare the header against our new 380 * options (in particular, snaplen) and adjust our options so 381 * that we generate a correct file. Furthermore, check the file 382 * for consistency so that we can append safely. 383 * 384 * XXX this may take a long time for large logs. 385 */ 386 fseek(fp, 0L, SEEK_SET); 387 388 if (fread((char *)&hdr, sizeof(hdr), 1, fp) != 1) { 389 logmsg(LOG_ERR, "Short file header"); 390 return (1); 391 } 392 393 if (hdr.magic != TCPDUMP_MAGIC || 394 hdr.version_major != PCAP_VERSION_MAJOR || 395 hdr.version_minor != PCAP_VERSION_MINOR || 396 (int)hdr.linktype != hpcap->linktype || 397 hdr.snaplen > PFLOGD_MAXSNAPLEN) { 398 return (1); 399 } 400 401 pos = sizeof(hdr); 402 403 while (!feof(fp)) { 404 off_t len = fread((char *)&ph, 1, sizeof(ph), fp); 405 if (len == 0) 406 break; 407 408 if (len != sizeof(ph)) 409 goto error; 410 if (ph.caplen > hdr.snaplen || ph.caplen > PFLOGD_MAXSNAPLEN) 411 goto error; 412 pos += sizeof(ph) + ph.caplen; 413 if (pos > size) 414 goto error; 415 fseek(fp, ph.caplen, SEEK_CUR); 416 } 417 418 if (pos != size) 419 goto error; 420 421 if ((int)hdr.snaplen != cur_snaplen) { 422 logmsg(LOG_WARNING, 423 "Existing file has different snaplen %u, using it", 424 hdr.snaplen); 425 if (set_snaplen(hdr.snaplen)) { 426 logmsg(LOG_WARNING, 427 "Failed, using old settings, offset %llu", 428 (unsigned long long) size); 429 } 430 } 431 432 return (0); 433 434 error: 435 logmsg(LOG_ERR, "Corrupted log file."); 436 return (1); 437 } 438 439 /* dump a packet directly to the stream, which is unbuffered */ 440 void 441 dump_packet_nobuf(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) 442 { 443 FILE *f = (FILE *)user; 444 struct pcap_sf_pkthdr sh; 445 446 if (suspended) { 447 packets_dropped++; 448 return; 449 } 450 451 sh.ts.tv_sec = (bpf_int32)h->ts.tv_sec; 452 sh.ts.tv_usec = (bpf_int32)h->ts.tv_usec; 453 sh.caplen = h->caplen; 454 sh.len = h->len; 455 456 if (fwrite((char *)&sh, sizeof(sh), 1, f) != 1) { 457 off_t pos = ftello(f); 458 459 /* try to undo header to prevent corruption */ 460 if ((size_t)pos < sizeof(sh) || 461 ftruncate(fileno(f), pos - sizeof(sh))) { 462 logmsg(LOG_ERR, "Write failed, corrupted logfile!"); 463 set_suspended(1); 464 gotsig_close = 1; 465 return; 466 } 467 goto error; 468 } 469 470 if (fwrite(sp, h->caplen, 1, f) != 1) 471 goto error; 472 473 return; 474 475 error: 476 set_suspended(1); 477 packets_dropped ++; 478 logmsg(LOG_ERR, "Logging suspended: fwrite: %s", strerror(errno)); 479 } 480 481 int 482 flush_buffer(FILE *f) 483 { 484 off_t offset; 485 int len = bufpos - buffer; 486 487 if (len <= 0) 488 return (0); 489 490 offset = ftello(f); 491 if (offset == (off_t)-1) { 492 set_suspended(1); 493 logmsg(LOG_ERR, "Logging suspended: ftello: %s", 494 strerror(errno)); 495 return (1); 496 } 497 498 if (fwrite(buffer, len, 1, f) != 1) { 499 set_suspended(1); 500 logmsg(LOG_ERR, "Logging suspended: fwrite: %s", 501 strerror(errno)); 502 ftruncate(fileno(f), offset); 503 return (1); 504 } 505 506 set_suspended(0); 507 bufpos = buffer; 508 bufleft = buflen; 509 bufpkt = 0; 510 511 return (0); 512 } 513 514 void 515 purge_buffer(void) 516 { 517 packets_dropped += bufpkt; 518 519 set_suspended(0); 520 bufpos = buffer; 521 bufleft = buflen; 522 bufpkt = 0; 523 } 524 525 /* append packet to the buffer, flushing if necessary */ 526 void 527 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) 528 { 529 FILE *f = (FILE *)user; 530 struct pcap_sf_pkthdr sh; 531 size_t len = sizeof(sh) + h->caplen; 532 533 if (len < sizeof(*h) || h->caplen > (size_t)cur_snaplen) { 534 logmsg(LOG_NOTICE, "invalid size %zd (%u/%u), packet dropped", 535 len, cur_snaplen, snaplen); 536 packets_dropped++; 537 return; 538 } 539 540 if (len <= bufleft) 541 goto append; 542 543 if (suspended) { 544 packets_dropped++; 545 return; 546 } 547 548 if (flush_buffer(f)) { 549 packets_dropped++; 550 return; 551 } 552 553 if (len > bufleft) { 554 dump_packet_nobuf(user, h, sp); 555 return; 556 } 557 558 append: 559 sh.ts.tv_sec = (bpf_int32)h->ts.tv_sec; 560 sh.ts.tv_usec = (bpf_int32)h->ts.tv_usec; 561 sh.caplen = h->caplen; 562 sh.len = h->len; 563 564 memcpy(bufpos, &sh, sizeof(sh)); 565 memcpy(bufpos + sizeof(sh), sp, h->caplen); 566 567 bufpos += len; 568 bufleft -= len; 569 bufpkt++; 570 571 return; 572 } 573 574 int 575 main(int argc, char **argv) 576 { 577 struct pcap_stat pstat; 578 int ch, np, ret, Xflag = 0; 579 pcap_handler phandler = dump_packet; 580 const char *errstr = NULL; 581 struct pidfh *pfh = NULL; 582 char *pidf = NULL; 583 584 ret = 0; 585 586 /* Neither FreeBSD nor DFly have this; Max seems to think this may 587 * be a paranoid check. Comment it out: 588 closefrom(STDERR_FILENO + 1); 589 */ 590 591 while ((ch = getopt(argc, argv, "Dxd:f:i:p:s:")) != -1) { 592 switch (ch) { 593 case 'D': 594 Debug = 1; 595 break; 596 case 'd': 597 delay = strtonum(optarg, 5, 60*60, &errstr); 598 if (errstr) 599 usage(); 600 break; 601 case 'f': 602 filename = optarg; 603 break; 604 case 'i': 605 interface = optarg; 606 break; 607 case 'p': 608 pidf = optarg; 609 break; 610 case 's': 611 snaplen = strtonum(optarg, 0, PFLOGD_MAXSNAPLEN, 612 &errstr); 613 if (snaplen <= 0) 614 snaplen = DEF_SNAPLEN; 615 if (errstr) 616 snaplen = PFLOGD_MAXSNAPLEN; 617 break; 618 case 'x': 619 Xflag++; 620 break; 621 default: 622 usage(); 623 } 624 625 } 626 627 log_debug = Debug; 628 argc -= optind; 629 argv += optind; 630 631 /* does interface exist */ 632 if (!if_exists(__DECONST(char *, interface))) { 633 warn("Failed to initialize: %s", interface); 634 logmsg(LOG_ERR, "Failed to initialize: %s", interface); 635 logmsg(LOG_ERR, "Exiting, init failure"); 636 exit(1); 637 } 638 639 if (!Debug) { 640 openlog("pflogd", LOG_PID | LOG_CONS, LOG_DAEMON); 641 pfh = pidfile_open(pidf, 0600, NULL); 642 if (daemon(0, 0)) { 643 logmsg(LOG_WARNING, "Failed to become daemon: %s", 644 strerror(errno)); 645 } 646 pidfile_write(pfh); 647 } 648 649 umask(S_IRWXG | S_IRWXO); 650 651 /* filter will be used by the privileged process */ 652 if (argc) { 653 filter = copy_argv(argv); 654 if (filter == NULL) 655 logmsg(LOG_NOTICE, "Failed to form filter expression"); 656 } 657 658 /* initialize pcap before dropping privileges */ 659 if (init_pcap()) { 660 logmsg(LOG_ERR, "Exiting, init failure"); 661 exit(1); 662 } 663 664 /* Privilege separation begins here */ 665 if (priv_init()) { 666 logmsg(LOG_ERR, "unable to privsep"); 667 exit(1); 668 } 669 670 setproctitle("[initializing]"); 671 /* Process is now unprivileged and inside a chroot */ 672 signal(SIGTERM, sig_close); 673 signal(SIGINT, sig_close); 674 signal(SIGQUIT, sig_close); 675 signal(SIGALRM, sig_alrm); 676 signal(SIGHUP, sig_hup); 677 alarm(delay); 678 679 buffer = malloc(PFLOGD_BUFSIZE); 680 681 if (buffer == NULL) { 682 logmsg(LOG_WARNING, "Failed to allocate output buffer"); 683 phandler = dump_packet_nobuf; 684 } else { 685 bufleft = buflen = PFLOGD_BUFSIZE; 686 bufpos = buffer; 687 bufpkt = 0; 688 } 689 690 if (reset_dump(Xflag) < 0) { 691 if (Xflag) 692 return (1); 693 694 logmsg(LOG_ERR, "Logging suspended: open error"); 695 set_suspended(1); 696 } else if (Xflag) 697 return (0); 698 699 while (1) { 700 np = pcap_dispatch(hpcap, PCAP_NUM_PKTS, 701 phandler, (u_char *)dpcap); 702 if (np < 0) { 703 if (!if_exists(__DECONST(char *, interface)) == -1) { 704 logmsg(LOG_NOTICE, "interface %s went away", 705 interface); 706 ret = -1; 707 break; 708 } 709 logmsg(LOG_NOTICE, "%s", pcap_geterr(hpcap)); 710 } 711 712 if (gotsig_close) 713 break; 714 if (gotsig_hup) { 715 if (reset_dump(0)) { 716 logmsg(LOG_ERR, 717 "Logging suspended: open error"); 718 set_suspended(1); 719 } 720 gotsig_hup = 0; 721 } 722 723 if (gotsig_alrm) { 724 if (dpcap) 725 flush_buffer(dpcap); 726 else 727 gotsig_hup = 1; 728 gotsig_alrm = 0; 729 alarm(delay); 730 } 731 } 732 733 logmsg(LOG_NOTICE, "Exiting"); 734 if (dpcap) { 735 flush_buffer(dpcap); 736 fclose(dpcap); 737 } 738 purge_buffer(); 739 740 if (pcap_stats(hpcap, &pstat) < 0) 741 logmsg(LOG_WARNING, "Reading stats: %s", pcap_geterr(hpcap)); 742 else 743 logmsg(LOG_NOTICE, 744 "%u packets received, %u/%ld dropped (kernel/pflogd)", 745 pstat.ps_recv, pstat.ps_drop, packets_dropped); 746 747 pcap_close(hpcap); 748 if (!Debug) 749 closelog(); 750 return (ret); 751 } 752