1 /* $OpenBSD: pflogd.c,v 1.46 2008/10/22 08:16:49 henning Exp $ */
4 * Copyright (c) 2001 Theo de Raadt
5 * Copyright (c) 2001 Can Erkin Acar
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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.
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
36 #include <sys/types.h>
37 #include <sys/ioctl.h>
40 #include <sys/socket.h>
67 static int snaplen = DEF_SNAPLEN;
68 static int cur_snaplen = DEF_SNAPLEN;
70 volatile sig_atomic_t gotsig_close, gotsig_alrm, gotsig_hup, gotsig_usr1;
72 char *filename = PFLOGD_LOG_FILE;
73 char *interface = PFLOGD_DEFAULT_IF;
76 char errbuf[PCAP_ERRBUF_SIZE];
79 unsigned int delay = FLUSH_DELAY;
81 char *copy_argv(char * const *);
82 void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
83 void dump_packet_nobuf(u_char *, const struct pcap_pkthdr *, const u_char *);
84 void log_pcap_stats(void);
85 int flush_buffer(FILE *);
86 int if_exists(char *);
88 void logmsg(int, const char *, ...);
89 void purge_buffer(void);
91 int scan_dump(FILE *, off_t);
93 void set_suspended(int);
100 static int try_reset_dump(int);
102 /* buffer must always be greater than snaplen */
103 static int bufpkt = 0; /* number of packets in buffer */
104 static int buflen = 0; /* allocated size of buffer */
105 static char *buffer = NULL; /* packet buffer */
106 static char *bufpos = NULL; /* position in buffer */
107 static int bufleft = 0; /* bytes left in buffer */
109 /* if error, stop logging but count dropped packets */
110 static int suspended = -1;
111 static long packets_dropped = 0;
120 setproctitle("[%s] -s %d -i %s -f %s",
121 suspended ? "suspended" : "running",
122 cur_snaplen, interface, filename);
126 copy_argv(char * const *argv)
134 for (n = 0; argv[n]; n++)
135 len += strlen(argv[n])+1;
143 strlcpy(buf, argv[0], len);
144 for (n = 1; argv[n]; n++) {
145 strlcat(buf, " ", len);
146 strlcat(buf, argv[n], len);
152 logmsg(int pri, const char *message, ...)
155 va_start(ap, message);
158 vfprintf(stderr, message, ap);
159 fprintf(stderr, "\n");
161 vsyslog(pri, message, ap);
172 fprintf(stderr, "usage: pflogd [-Dx] [-d delay] [-f filename]");
173 fprintf(stderr, " [-i interface] [-p pidfile]\n");
174 fprintf(stderr, " [-s snaplen] [expression]\n");
203 set_pcap_filter(void)
205 struct bpf_program bprog;
207 if (pcap_compile(hpcap, &bprog, filter, PCAP_OPT_FIL, 0) < 0)
208 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
210 if (pcap_setfilter(hpcap, &bprog) < 0)
211 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
212 pcap_freecode(&bprog);
217 if_exists(char *ifname)
220 struct ifaddrs *ifdata, *mb;
227 for (mb = ifdata; mb != NULL; mb = mb->ifa_next) {
230 if (strlen(ifname) != strlen(mb->ifa_name))
232 if (strncmp(ifname, mb->ifa_name, strlen(ifname)) != 0)
243 struct if_data ifrdat;
245 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
247 bzero(&ifr, sizeof(ifr));
248 if (strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)) >=
249 sizeof(ifr.ifr_name))
250 errx(1, "main ifr_name: strlcpy");
251 ifr.ifr_data = (caddr_t)&ifrdat;
252 if (ioctl(s, SIOCGIFDATA, (caddr_t)&ifr) == -1)
264 hpcap = pcap_open_live(interface, snaplen, 1, PCAP_TO_MS, errbuf);
266 logmsg(LOG_ERR, "Failed to initialize: %s", errbuf);
270 if (pcap_datalink(hpcap) != DLT_PFLOG) {
271 logmsg(LOG_ERR, "Invalid datalink type");
279 cur_snaplen = snaplen = pcap_snapshot(hpcap);
282 if (ioctl(pcap_fileno(hpcap), BIOCLOCK) < 0) {
283 logmsg(LOG_ERR, "BIOCLOCK: %s", strerror(errno));
291 set_snaplen(int snap)
293 if (priv_set_snaplen(snap))
296 if (cur_snaplen > snap)
305 reset_dump(int nomove)
310 ret = try_reset_dump(nomove);
319 * tries to (re)open log file, nomove flag is used with -x switch
320 * returns 0: success, 1: retry (log moved), -1: error
323 try_reset_dump(int nomove)
325 struct pcap_file_header hdr;
340 * Basically reimplement pcap_dump_open() because it truncates
341 * files and duplicates headers and such.
343 fd = priv_open_log();
347 fp = fdopen(fd, "a+");
350 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
354 if (fstat(fileno(fp), &st) == -1) {
355 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
360 /* set FILE unbuffered, we do our own buffering */
361 if (setvbuf(fp, NULL, _IONBF, 0)) {
362 logmsg(LOG_ERR, "Failed to set output buffers");
367 #define TCPDUMP_MAGIC 0xa1b2c3d4
369 if (st.st_size == 0) {
370 if (snaplen != cur_snaplen) {
371 logmsg(LOG_NOTICE, "Using snaplen %d", snaplen);
372 if (set_snaplen(snaplen))
374 "Failed, using old settings");
376 hdr.magic = TCPDUMP_MAGIC;
377 hdr.version_major = PCAP_VERSION_MAJOR;
378 hdr.version_minor = PCAP_VERSION_MINOR;
379 hdr.thiszone = hpcap->tzoff;
380 hdr.snaplen = hpcap->snapshot;
382 hdr.linktype = hpcap->linktype;
384 if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
388 } else if (scan_dump(fp, st.st_size)) {
390 if (nomove || priv_move_log()) {
392 "Invalid/incompatible log file, move it away");
407 scan_dump(FILE *fp, off_t size)
409 struct pcap_file_header hdr;
411 struct pcap_sf_pkthdr ph;
413 struct pcap_pkthdr ph;
418 * Must read the file, compare the header against our new
419 * options (in particular, snaplen) and adjust our options so
420 * that we generate a correct file. Furthermore, check the file
421 * for consistency so that we can append safely.
423 * XXX this may take a long time for large logs.
425 (void) fseek(fp, 0L, SEEK_SET);
427 if (fread((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
428 logmsg(LOG_ERR, "Short file header");
432 if (hdr.magic != TCPDUMP_MAGIC ||
433 hdr.version_major != PCAP_VERSION_MAJOR ||
434 hdr.version_minor != PCAP_VERSION_MINOR ||
435 hdr.linktype != hpcap->linktype ||
436 hdr.snaplen > PFLOGD_MAXSNAPLEN) {
443 off_t len = fread((char *)&ph, 1, sizeof(ph), fp);
447 if (len != sizeof(ph))
449 if (ph.caplen > hdr.snaplen || ph.caplen > PFLOGD_MAXSNAPLEN)
451 pos += sizeof(ph) + ph.caplen;
454 fseek(fp, ph.caplen, SEEK_CUR);
460 if (hdr.snaplen != cur_snaplen) {
462 "Existing file has different snaplen %u, using it",
464 if (set_snaplen(hdr.snaplen)) {
466 "Failed, using old settings, offset %llu",
467 (unsigned long long) size);
474 logmsg(LOG_ERR, "Corrupted log file.");
478 /* dump a packet directly to the stream, which is unbuffered */
480 dump_packet_nobuf(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
482 FILE *f = (FILE *)user;
484 struct pcap_sf_pkthdr sh;
493 sh.ts.tv_sec = (bpf_int32)h->ts.tv_sec;
494 sh.ts.tv_usec = (bpf_int32)h->ts.tv_usec;
495 sh.caplen = h->caplen;
498 if (fwrite((char *)&sh, sizeof(sh), 1, f) != 1) {
500 if (fwrite((char *)h, sizeof(*h), 1, f) != 1) {
502 off_t pos = ftello(f);
504 /* try to undo header to prevent corruption */
506 if (pos < sizeof(sh) ||
507 ftruncate(fileno(f), pos - sizeof(sh))) {
509 if (pos < sizeof(*h) ||
510 ftruncate(fileno(f), pos - sizeof(*h))) {
512 logmsg(LOG_ERR, "Write failed, corrupted logfile!");
520 if (fwrite((char *)sp, h->caplen, 1, f) != 1)
528 logmsg(LOG_ERR, "Logging suspended: fwrite: %s", strerror(errno));
532 flush_buffer(FILE *f)
535 int len = bufpos - buffer;
541 if (offset == (off_t)-1) {
543 logmsg(LOG_ERR, "Logging suspended: ftello: %s",
548 if (fwrite(buffer, len, 1, f) != 1) {
550 logmsg(LOG_ERR, "Logging suspended: fwrite: %s",
552 ftruncate(fileno(f), offset);
567 packets_dropped += bufpkt;
575 /* append packet to the buffer, flushing if necessary */
577 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
579 FILE *f = (FILE *)user;
581 struct pcap_sf_pkthdr sh;
582 size_t len = sizeof(sh) + h->caplen;
584 size_t len = sizeof(*h) + h->caplen;
587 if (len < sizeof(*h) || h->caplen > (size_t)cur_snaplen) {
588 logmsg(LOG_NOTICE, "invalid size %u (%u/%u), packet dropped",
589 len, cur_snaplen, snaplen);
602 if (flush_buffer(f)) {
608 dump_packet_nobuf(user, h, sp);
614 sh.ts.tv_sec = (bpf_int32)h->ts.tv_sec;
615 sh.ts.tv_usec = (bpf_int32)h->ts.tv_usec;
616 sh.caplen = h->caplen;
619 memcpy(bufpos, &sh, sizeof(sh));
620 memcpy(bufpos + sizeof(sh), sp, h->caplen);
622 memcpy(bufpos, h, sizeof(*h));
623 memcpy(bufpos + sizeof(*h), sp, h->caplen);
636 struct pcap_stat pstat;
637 if (pcap_stats(hpcap, &pstat) < 0)
638 logmsg(LOG_WARNING, "Reading stats: %s", pcap_geterr(hpcap));
641 "%u packets received, %u/%u dropped (kernel/pflogd)",
642 pstat.ps_recv, pstat.ps_drop, packets_dropped);
646 main(int argc, char **argv)
648 int ch, np, ret, Xflag = 0;
649 pcap_handler phandler = dump_packet;
650 const char *errstr = NULL;
655 closefrom(STDERR_FILENO + 1);
657 while ((ch = getopt(argc, argv, "Dxd:f:i:p:s:")) != -1) {
663 delay = strtonum(optarg, 5, 60*60, &errstr);
677 snaplen = strtonum(optarg, 0, PFLOGD_MAXSNAPLEN,
680 snaplen = DEF_SNAPLEN;
682 snaplen = PFLOGD_MAXSNAPLEN;
697 /* does interface exist */
698 if (!if_exists(interface)) {
699 warn("Failed to initialize: %s", interface);
700 logmsg(LOG_ERR, "Failed to initialize: %s", interface);
701 logmsg(LOG_ERR, "Exiting, init failure");
706 openlog("pflogd", LOG_PID | LOG_CONS, LOG_DAEMON);
708 logmsg(LOG_WARNING, "Failed to become daemon: %s",
715 (void)umask(S_IRWXG | S_IRWXO);
717 /* filter will be used by the privileged process */
719 filter = copy_argv(argv);
721 logmsg(LOG_NOTICE, "Failed to form filter expression");
724 /* initialize pcap before dropping privileges */
726 logmsg(LOG_ERR, "Exiting, init failure");
730 /* Privilege separation begins here */
732 logmsg(LOG_ERR, "unable to privsep");
736 setproctitle("[initializing]");
737 /* Process is now unprivileged and inside a chroot */
738 signal(SIGTERM, sig_close);
739 signal(SIGINT, sig_close);
740 signal(SIGQUIT, sig_close);
741 signal(SIGALRM, sig_alrm);
742 signal(SIGUSR1, sig_usr1);
743 signal(SIGHUP, sig_hup);
746 buffer = malloc(PFLOGD_BUFSIZE);
748 if (buffer == NULL) {
749 logmsg(LOG_WARNING, "Failed to allocate output buffer");
750 phandler = dump_packet_nobuf;
752 bufleft = buflen = PFLOGD_BUFSIZE;
757 if (reset_dump(Xflag) < 0) {
761 logmsg(LOG_ERR, "Logging suspended: open error");
767 np = pcap_dispatch(hpcap, PCAP_NUM_PKTS,
768 phandler, (u_char *)dpcap);
770 if (!if_exists(interface)) {
771 logmsg(LOG_NOTICE, "interface %s went away",
776 logmsg(LOG_NOTICE, "%s", pcap_geterr(hpcap));
784 "Logging suspended: open error");
805 logmsg(LOG_NOTICE, "Exiting");