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/types.h>
34 #include <sys/ioctl.h>
37 #include <sys/socket.h>
63 static int snaplen = DEF_SNAPLEN;
64 static int cur_snaplen = DEF_SNAPLEN;
66 volatile sig_atomic_t gotsig_close, gotsig_alrm, gotsig_hup, gotsig_usr1;
68 char *filename = PFLOGD_LOG_FILE;
69 char *interface = PFLOGD_DEFAULT_IF;
72 char errbuf[PCAP_ERRBUF_SIZE];
75 unsigned int delay = FLUSH_DELAY;
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 void log_pcap_stats(void);
81 int flush_buffer(FILE *);
82 int if_exists(char *);
84 void logmsg(int, const char *, ...);
85 void purge_buffer(void);
87 int scan_dump(FILE *, off_t);
89 void set_suspended(int);
96 static int try_reset_dump(int);
98 /* buffer must always be greater than snaplen */
99 static int bufpkt = 0; /* number of packets in buffer */
100 static int buflen = 0; /* allocated size of buffer */
101 static char *buffer = NULL; /* packet buffer */
102 static char *bufpos = NULL; /* position in buffer */
103 static int bufleft = 0; /* bytes left in buffer */
105 /* if error, stop logging but count dropped packets */
106 static int suspended = -1;
107 static long packets_dropped = 0;
116 setproctitle("[%s] -s %d -i %s -f %s",
117 suspended ? "suspended" : "running",
118 cur_snaplen, interface, filename);
122 copy_argv(char * const *argv)
130 for (n = 0; argv[n]; n++)
131 len += strlen(argv[n])+1;
139 strlcpy(buf, argv[0], len);
140 for (n = 1; argv[n]; n++) {
141 strlcat(buf, " ", len);
142 strlcat(buf, argv[n], len);
148 logmsg(int pri, const char *message, ...)
151 va_start(ap, message);
154 vfprintf(stderr, message, ap);
155 fprintf(stderr, "\n");
157 vsyslog(pri, message, ap);
168 fprintf(stderr, "usage: pflogd [-Dx] [-d delay] [-f filename]");
169 fprintf(stderr, " [-i interface] [-p pidfile]\n");
170 fprintf(stderr, " [-s snaplen] [expression]\n");
199 set_pcap_filter(void)
201 struct bpf_program bprog;
203 if (pcap_compile(hpcap, &bprog, filter, PCAP_OPT_FIL, 0) < 0)
204 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
206 if (pcap_setfilter(hpcap, &bprog) < 0)
207 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
208 pcap_freecode(&bprog);
213 if_exists(char *ifname)
216 struct ifaddrs *ifdata, *mb;
223 for (mb = ifdata; mb != NULL; mb = mb->ifa_next) {
226 if (strlen(ifname) != strlen(mb->ifa_name))
228 if (strncmp(ifname, mb->ifa_name, strlen(ifname)) != 0)
239 struct if_data ifrdat;
241 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
243 bzero(&ifr, sizeof(ifr));
244 if (strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)) >=
245 sizeof(ifr.ifr_name))
246 errx(1, "main ifr_name: strlcpy");
247 ifr.ifr_data = (caddr_t)&ifrdat;
248 if (ioctl(s, SIOCGIFDATA, (caddr_t)&ifr) == -1)
260 hpcap = pcap_open_live(interface, snaplen, 1, PCAP_TO_MS, errbuf);
262 logmsg(LOG_ERR, "Failed to initialize: %s", errbuf);
266 if (pcap_datalink(hpcap) != DLT_PFLOG) {
267 logmsg(LOG_ERR, "Invalid datalink type");
275 cur_snaplen = snaplen = pcap_snapshot(hpcap);
278 if (ioctl(pcap_fileno(hpcap), BIOCLOCK) < 0) {
279 logmsg(LOG_ERR, "BIOCLOCK: %s", strerror(errno));
287 set_snaplen(int snap)
289 if (priv_set_snaplen(snap))
292 if (cur_snaplen > snap)
301 reset_dump(int nomove)
306 ret = try_reset_dump(nomove);
315 * tries to (re)open log file, nomove flag is used with -x switch
316 * returns 0: success, 1: retry (log moved), -1: error
319 try_reset_dump(int nomove)
321 struct pcap_file_header hdr;
336 * Basically reimplement pcap_dump_open() because it truncates
337 * files and duplicates headers and such.
339 fd = priv_open_log();
343 fp = fdopen(fd, "a+");
346 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
350 if (fstat(fileno(fp), &st) == -1) {
351 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
356 /* set FILE unbuffered, we do our own buffering */
357 if (setvbuf(fp, NULL, _IONBF, 0)) {
358 logmsg(LOG_ERR, "Failed to set output buffers");
363 #define TCPDUMP_MAGIC 0xa1b2c3d4
365 if (st.st_size == 0) {
366 if (snaplen != cur_snaplen) {
367 logmsg(LOG_NOTICE, "Using snaplen %d", snaplen);
368 if (set_snaplen(snaplen))
370 "Failed, using old settings");
372 hdr.magic = TCPDUMP_MAGIC;
373 hdr.version_major = PCAP_VERSION_MAJOR;
374 hdr.version_minor = PCAP_VERSION_MINOR;
376 hdr.snaplen = hpcap->snapshot;
378 hdr.linktype = hpcap->linktype;
380 if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
384 } else if (scan_dump(fp, st.st_size)) {
386 if (nomove || priv_move_log()) {
388 "Invalid/incompatible log file, move it away");
403 scan_dump(FILE *fp, off_t size)
405 struct pcap_file_header hdr;
407 struct pcap_sf_pkthdr ph;
409 struct pcap_pkthdr ph;
414 * Must read the file, compare the header against our new
415 * options (in particular, snaplen) and adjust our options so
416 * that we generate a correct file. Furthermore, check the file
417 * for consistency so that we can append safely.
419 * XXX this may take a long time for large logs.
421 (void) fseek(fp, 0L, SEEK_SET);
423 if (fread((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
424 logmsg(LOG_ERR, "Short file header");
428 if (hdr.magic != TCPDUMP_MAGIC ||
429 hdr.version_major != PCAP_VERSION_MAJOR ||
430 hdr.version_minor != PCAP_VERSION_MINOR ||
431 hdr.linktype != hpcap->linktype ||
432 hdr.snaplen > PFLOGD_MAXSNAPLEN) {
439 off_t len = fread((char *)&ph, 1, sizeof(ph), fp);
443 if (len != sizeof(ph))
445 if (ph.caplen > hdr.snaplen || ph.caplen > PFLOGD_MAXSNAPLEN)
447 pos += sizeof(ph) + ph.caplen;
450 fseek(fp, ph.caplen, SEEK_CUR);
456 if (hdr.snaplen != cur_snaplen) {
458 "Existing file has different snaplen %u, using it",
460 if (set_snaplen(hdr.snaplen)) {
462 "Failed, using old settings, offset %llu",
463 (unsigned long long) size);
470 logmsg(LOG_ERR, "Corrupted log file.");
474 /* dump a packet directly to the stream, which is unbuffered */
476 dump_packet_nobuf(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
478 FILE *f = (FILE *)user;
480 struct pcap_sf_pkthdr sh;
489 sh.ts.tv_sec = (bpf_int32)h->ts.tv_sec;
490 sh.ts.tv_usec = (bpf_int32)h->ts.tv_usec;
491 sh.caplen = h->caplen;
494 if (fwrite((char *)&sh, sizeof(sh), 1, f) != 1) {
496 if (fwrite((char *)h, sizeof(*h), 1, f) != 1) {
498 off_t pos = ftello(f);
500 /* try to undo header to prevent corruption */
502 if (pos < sizeof(sh) ||
503 ftruncate(fileno(f), pos - sizeof(sh))) {
505 if (pos < sizeof(*h) ||
506 ftruncate(fileno(f), pos - sizeof(*h))) {
508 logmsg(LOG_ERR, "Write failed, corrupted logfile!");
516 if (fwrite((char *)sp, h->caplen, 1, f) != 1)
524 logmsg(LOG_ERR, "Logging suspended: fwrite: %s", strerror(errno));
528 flush_buffer(FILE *f)
531 int len = bufpos - buffer;
537 if (offset == (off_t)-1) {
539 logmsg(LOG_ERR, "Logging suspended: ftello: %s",
544 if (fwrite(buffer, len, 1, f) != 1) {
546 logmsg(LOG_ERR, "Logging suspended: fwrite: %s",
548 ftruncate(fileno(f), offset);
563 packets_dropped += bufpkt;
571 /* append packet to the buffer, flushing if necessary */
573 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
575 FILE *f = (FILE *)user;
577 struct pcap_sf_pkthdr sh;
578 size_t len = sizeof(sh) + h->caplen;
580 size_t len = sizeof(*h) + h->caplen;
583 if (len < sizeof(*h) || h->caplen > (size_t)cur_snaplen) {
584 logmsg(LOG_NOTICE, "invalid size %u (%u/%u), packet dropped",
585 len, cur_snaplen, snaplen);
598 if (flush_buffer(f)) {
604 dump_packet_nobuf(user, h, sp);
610 sh.ts.tv_sec = (bpf_int32)h->ts.tv_sec;
611 sh.ts.tv_usec = (bpf_int32)h->ts.tv_usec;
612 sh.caplen = h->caplen;
615 memcpy(bufpos, &sh, sizeof(sh));
616 memcpy(bufpos + sizeof(sh), sp, h->caplen);
618 memcpy(bufpos, h, sizeof(*h));
619 memcpy(bufpos + sizeof(*h), sp, h->caplen);
632 struct pcap_stat pstat;
633 if (pcap_stats(hpcap, &pstat) < 0)
634 logmsg(LOG_WARNING, "Reading stats: %s", pcap_geterr(hpcap));
637 "%u packets received, %u/%u dropped (kernel/pflogd)",
638 pstat.ps_recv, pstat.ps_drop, packets_dropped);
642 main(int argc, char **argv)
644 int ch, np, ret, Xflag = 0;
645 pcap_handler phandler = dump_packet;
646 const char *errstr = NULL;
651 closefrom(STDERR_FILENO + 1);
653 while ((ch = getopt(argc, argv, "Dxd:f:i:p:s:")) != -1) {
659 delay = strtonum(optarg, 5, 60*60, &errstr);
673 snaplen = strtonum(optarg, 0, PFLOGD_MAXSNAPLEN,
676 snaplen = DEF_SNAPLEN;
678 snaplen = PFLOGD_MAXSNAPLEN;
693 /* does interface exist */
694 if (!if_exists(interface)) {
695 warn("Failed to initialize: %s", interface);
696 logmsg(LOG_ERR, "Failed to initialize: %s", interface);
697 logmsg(LOG_ERR, "Exiting, init failure");
702 openlog("pflogd", LOG_PID | LOG_CONS, LOG_DAEMON);
704 logmsg(LOG_WARNING, "Failed to become daemon: %s",
711 (void)umask(S_IRWXG | S_IRWXO);
713 /* filter will be used by the privileged process */
715 filter = copy_argv(argv);
717 logmsg(LOG_NOTICE, "Failed to form filter expression");
720 /* initialize pcap before dropping privileges */
722 logmsg(LOG_ERR, "Exiting, init failure");
726 /* Privilege separation begins here */
728 logmsg(LOG_ERR, "unable to privsep");
732 setproctitle("[initializing]");
733 /* Process is now unprivileged and inside a chroot */
734 signal(SIGTERM, sig_close);
735 signal(SIGINT, sig_close);
736 signal(SIGQUIT, sig_close);
737 signal(SIGALRM, sig_alrm);
738 signal(SIGUSR1, sig_usr1);
739 signal(SIGHUP, sig_hup);
742 buffer = malloc(PFLOGD_BUFSIZE);
744 if (buffer == NULL) {
745 logmsg(LOG_WARNING, "Failed to allocate output buffer");
746 phandler = dump_packet_nobuf;
748 bufleft = buflen = PFLOGD_BUFSIZE;
753 if (reset_dump(Xflag) < 0) {
757 logmsg(LOG_ERR, "Logging suspended: open error");
763 np = pcap_dispatch(hpcap, PCAP_NUM_PKTS,
764 phandler, (u_char *)dpcap);
766 if (!if_exists(interface)) {
767 logmsg(LOG_NOTICE, "interface %s went away",
772 logmsg(LOG_NOTICE, "%s", pcap_geterr(hpcap));
780 "Logging suspended: open error");
801 logmsg(LOG_NOTICE, "Exiting");