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 445 if (suspended) { 446 packets_dropped++; 447 return; 448 } 449 450 if (fwrite(h, sizeof(*h), 1, f) != 1) { 451 off_t pos = ftello(f); 452 453 /* try to undo header to prevent corruption */ 454 if ((size_t)pos < sizeof(*h) || 455 ftruncate(fileno(f), pos - sizeof(*h))) { 456 logmsg(LOG_ERR, "Write failed, corrupted logfile!"); 457 set_suspended(1); 458 gotsig_close = 1; 459 return; 460 } 461 goto error; 462 } 463 464 if (fwrite(sp, h->caplen, 1, f) != 1) 465 goto error; 466 467 return; 468 469 error: 470 set_suspended(1); 471 packets_dropped ++; 472 logmsg(LOG_ERR, "Logging suspended: fwrite: %s", strerror(errno)); 473 } 474 475 int 476 flush_buffer(FILE *f) 477 { 478 off_t offset; 479 int len = bufpos - buffer; 480 481 if (len <= 0) 482 return (0); 483 484 offset = ftello(f); 485 if (offset == (off_t)-1) { 486 set_suspended(1); 487 logmsg(LOG_ERR, "Logging suspended: ftello: %s", 488 strerror(errno)); 489 return (1); 490 } 491 492 if (fwrite(buffer, len, 1, f) != 1) { 493 set_suspended(1); 494 logmsg(LOG_ERR, "Logging suspended: fwrite: %s", 495 strerror(errno)); 496 ftruncate(fileno(f), offset); 497 return (1); 498 } 499 500 set_suspended(0); 501 bufpos = buffer; 502 bufleft = buflen; 503 bufpkt = 0; 504 505 return (0); 506 } 507 508 void 509 purge_buffer(void) 510 { 511 packets_dropped += bufpkt; 512 513 set_suspended(0); 514 bufpos = buffer; 515 bufleft = buflen; 516 bufpkt = 0; 517 } 518 519 /* append packet to the buffer, flushing if necessary */ 520 void 521 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) 522 { 523 FILE *f = (FILE *)user; 524 size_t len = sizeof(*h) + h->caplen; 525 526 if (len < sizeof(*h) || h->caplen > (size_t)cur_snaplen) { 527 logmsg(LOG_NOTICE, "invalid size %zd (%u/%u), packet dropped", 528 len, cur_snaplen, snaplen); 529 packets_dropped++; 530 return; 531 } 532 533 if (len <= bufleft) 534 goto append; 535 536 if (suspended) { 537 packets_dropped++; 538 return; 539 } 540 541 if (flush_buffer(f)) { 542 packets_dropped++; 543 return; 544 } 545 546 if (len > bufleft) { 547 dump_packet_nobuf(user, h, sp); 548 return; 549 } 550 551 append: 552 memcpy(bufpos, h, sizeof(*h)); 553 memcpy(bufpos + sizeof(*h), sp, h->caplen); 554 555 bufpos += len; 556 bufleft -= len; 557 bufpkt++; 558 559 return; 560 } 561 562 int 563 main(int argc, char **argv) 564 { 565 struct pcap_stat pstat; 566 int ch, np, ret, Xflag = 0; 567 pcap_handler phandler = dump_packet; 568 const char *errstr = NULL; 569 struct pidfh *pfh = NULL; 570 char *pidf = NULL; 571 572 ret = 0; 573 574 /* Neither FreeBSD nor DFly have this; Max seems to think this may 575 * be a paranoid check. Comment it out: 576 closefrom(STDERR_FILENO + 1); 577 */ 578 579 while ((ch = getopt(argc, argv, "Dxd:f:i:p:s:")) != -1) { 580 switch (ch) { 581 case 'D': 582 Debug = 1; 583 break; 584 case 'd': 585 delay = strtonum(optarg, 5, 60*60, &errstr); 586 if (errstr) 587 usage(); 588 break; 589 case 'f': 590 filename = optarg; 591 break; 592 case 'i': 593 interface = optarg; 594 break; 595 case 'p': 596 pidf = optarg; 597 break; 598 case 's': 599 snaplen = strtonum(optarg, 0, PFLOGD_MAXSNAPLEN, 600 &errstr); 601 if (snaplen <= 0) 602 snaplen = DEF_SNAPLEN; 603 if (errstr) 604 snaplen = PFLOGD_MAXSNAPLEN; 605 break; 606 case 'x': 607 Xflag++; 608 break; 609 default: 610 usage(); 611 } 612 613 } 614 615 log_debug = Debug; 616 argc -= optind; 617 argv += optind; 618 619 /* does interface exist */ 620 if (!if_exists(__DECONST(char *, interface))) { 621 warn("Failed to initialize: %s", interface); 622 logmsg(LOG_ERR, "Failed to initialize: %s", interface); 623 logmsg(LOG_ERR, "Exiting, init failure"); 624 exit(1); 625 } 626 627 if (!Debug) { 628 openlog("pflogd", LOG_PID | LOG_CONS, LOG_DAEMON); 629 pfh = pidfile_open(pidf, 0600, NULL); 630 if (daemon(0, 0)) { 631 logmsg(LOG_WARNING, "Failed to become daemon: %s", 632 strerror(errno)); 633 } 634 pidfile_write(pfh); 635 } 636 637 umask(S_IRWXG | S_IRWXO); 638 639 /* filter will be used by the privileged process */ 640 if (argc) { 641 filter = copy_argv(argv); 642 if (filter == NULL) 643 logmsg(LOG_NOTICE, "Failed to form filter expression"); 644 } 645 646 /* initialize pcap before dropping privileges */ 647 if (init_pcap()) { 648 logmsg(LOG_ERR, "Exiting, init failure"); 649 exit(1); 650 } 651 652 /* Privilege separation begins here */ 653 if (priv_init()) { 654 logmsg(LOG_ERR, "unable to privsep"); 655 exit(1); 656 } 657 658 setproctitle("[initializing]"); 659 /* Process is now unprivileged and inside a chroot */ 660 signal(SIGTERM, sig_close); 661 signal(SIGINT, sig_close); 662 signal(SIGQUIT, sig_close); 663 signal(SIGALRM, sig_alrm); 664 signal(SIGHUP, sig_hup); 665 alarm(delay); 666 667 buffer = malloc(PFLOGD_BUFSIZE); 668 669 if (buffer == NULL) { 670 logmsg(LOG_WARNING, "Failed to allocate output buffer"); 671 phandler = dump_packet_nobuf; 672 } else { 673 bufleft = buflen = PFLOGD_BUFSIZE; 674 bufpos = buffer; 675 bufpkt = 0; 676 } 677 678 if (reset_dump(Xflag) < 0) { 679 if (Xflag) 680 return (1); 681 682 logmsg(LOG_ERR, "Logging suspended: open error"); 683 set_suspended(1); 684 } else if (Xflag) 685 return (0); 686 687 while (1) { 688 np = pcap_dispatch(hpcap, PCAP_NUM_PKTS, 689 phandler, (u_char *)dpcap); 690 if (np < 0) { 691 if (!if_exists(__DECONST(char *, interface)) == -1) { 692 logmsg(LOG_NOTICE, "interface %s went away", 693 interface); 694 ret = -1; 695 break; 696 } 697 logmsg(LOG_NOTICE, "%s", pcap_geterr(hpcap)); 698 } 699 700 if (gotsig_close) 701 break; 702 if (gotsig_hup) { 703 if (reset_dump(0)) { 704 logmsg(LOG_ERR, 705 "Logging suspended: open error"); 706 set_suspended(1); 707 } 708 gotsig_hup = 0; 709 } 710 711 if (gotsig_alrm) { 712 if (dpcap) 713 flush_buffer(dpcap); 714 else 715 gotsig_hup = 1; 716 gotsig_alrm = 0; 717 alarm(delay); 718 } 719 } 720 721 logmsg(LOG_NOTICE, "Exiting"); 722 if (dpcap) { 723 flush_buffer(dpcap); 724 fclose(dpcap); 725 } 726 purge_buffer(); 727 728 if (pcap_stats(hpcap, &pstat) < 0) 729 logmsg(LOG_WARNING, "Reading stats: %s", pcap_geterr(hpcap)); 730 else 731 logmsg(LOG_NOTICE, 732 "%u packets received, %u/%ld dropped (kernel/pflogd)", 733 pstat.ps_recv, pstat.ps_drop, packets_dropped); 734 735 pcap_close(hpcap); 736 if (!Debug) 737 closelog(); 738 return (ret); 739 } 740