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>
66 static int snaplen = DEF_SNAPLEN;
67 static int cur_snaplen = DEF_SNAPLEN;
69 volatile sig_atomic_t gotsig_close, gotsig_alrm, gotsig_hup, gotsig_usr1;
71 char *filename = PFLOGD_LOG_FILE;
72 char *interface = PFLOGD_DEFAULT_IF;
75 char errbuf[PCAP_ERRBUF_SIZE];
78 unsigned int delay = FLUSH_DELAY;
80 char *copy_argv(char * const *);
81 void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
82 void dump_packet_nobuf(u_char *, const struct pcap_pkthdr *, const u_char *);
83 void log_pcap_stats(void);
84 int flush_buffer(FILE *);
85 int if_exists(char *);
87 void logmsg(int, const char *, ...);
88 void purge_buffer(void);
90 int scan_dump(FILE *, off_t);
92 void set_suspended(int);
99 static int try_reset_dump(int);
101 /* buffer must always be greater than snaplen */
102 static int bufpkt = 0; /* number of packets in buffer */
103 static int buflen = 0; /* allocated size of buffer */
104 static char *buffer = NULL; /* packet buffer */
105 static char *bufpos = NULL; /* position in buffer */
106 static int bufleft = 0; /* bytes left in buffer */
108 /* if error, stop logging but count dropped packets */
109 static int suspended = -1;
110 static long packets_dropped = 0;
119 setproctitle("[%s] -s %d -i %s -f %s",
120 suspended ? "suspended" : "running",
121 cur_snaplen, interface, filename);
125 copy_argv(char * const *argv)
133 for (n = 0; argv[n]; n++)
134 len += strlen(argv[n])+1;
142 strlcpy(buf, argv[0], len);
143 for (n = 1; argv[n]; n++) {
144 strlcat(buf, " ", len);
145 strlcat(buf, argv[n], len);
151 logmsg(int pri, const char *message, ...)
154 va_start(ap, message);
157 vfprintf(stderr, message, ap);
158 fprintf(stderr, "\n");
160 vsyslog(pri, message, ap);
171 fprintf(stderr, "usage: pflogd [-Dx] [-d delay] [-f filename]");
172 fprintf(stderr, " [-i interface] [-p pidfile]\n");
173 fprintf(stderr, " [-s snaplen] [expression]\n");
202 set_pcap_filter(void)
204 struct bpf_program bprog;
206 if (pcap_compile(hpcap, &bprog, filter, PCAP_OPT_FIL, 0) < 0)
207 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
209 if (pcap_setfilter(hpcap, &bprog) < 0)
210 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
211 pcap_freecode(&bprog);
216 if_exists(char *ifname)
219 struct ifaddrs *ifdata, *mb;
226 for (mb = ifdata; mb != NULL; mb = mb->ifa_next) {
229 if (strlen(ifname) != strlen(mb->ifa_name))
231 if (strncmp(ifname, mb->ifa_name, strlen(ifname)) != 0)
242 struct if_data ifrdat;
244 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
246 bzero(&ifr, sizeof(ifr));
247 if (strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)) >=
248 sizeof(ifr.ifr_name))
249 errx(1, "main ifr_name: strlcpy");
250 ifr.ifr_data = (caddr_t)&ifrdat;
251 if (ioctl(s, SIOCGIFDATA, (caddr_t)&ifr) == -1)
263 hpcap = pcap_open_live(interface, snaplen, 1, PCAP_TO_MS, errbuf);
265 logmsg(LOG_ERR, "Failed to initialize: %s", errbuf);
269 if (pcap_datalink(hpcap) != DLT_PFLOG) {
270 logmsg(LOG_ERR, "Invalid datalink type");
278 cur_snaplen = snaplen = pcap_snapshot(hpcap);
281 if (ioctl(pcap_fileno(hpcap), BIOCLOCK) < 0) {
282 logmsg(LOG_ERR, "BIOCLOCK: %s", strerror(errno));
290 set_snaplen(int snap)
292 if (priv_set_snaplen(snap))
295 if (cur_snaplen > snap)
304 reset_dump(int nomove)
309 ret = try_reset_dump(nomove);
318 * tries to (re)open log file, nomove flag is used with -x switch
319 * returns 0: success, 1: retry (log moved), -1: error
322 try_reset_dump(int nomove)
324 struct pcap_file_header hdr;
339 * Basically reimplement pcap_dump_open() because it truncates
340 * files and duplicates headers and such.
342 fd = priv_open_log();
346 fp = fdopen(fd, "a+");
349 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
353 if (fstat(fileno(fp), &st) == -1) {
354 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
359 /* set FILE unbuffered, we do our own buffering */
360 if (setvbuf(fp, NULL, _IONBF, 0)) {
361 logmsg(LOG_ERR, "Failed to set output buffers");
366 #define TCPDUMP_MAGIC 0xa1b2c3d4
368 if (st.st_size == 0) {
369 if (snaplen != cur_snaplen) {
370 logmsg(LOG_NOTICE, "Using snaplen %d", snaplen);
371 if (set_snaplen(snaplen))
373 "Failed, using old settings");
375 hdr.magic = TCPDUMP_MAGIC;
376 hdr.version_major = PCAP_VERSION_MAJOR;
377 hdr.version_minor = PCAP_VERSION_MINOR;
378 hdr.thiszone = hpcap->tzoff;
379 hdr.snaplen = hpcap->snapshot;
381 hdr.linktype = hpcap->linktype;
383 if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
387 } else if (scan_dump(fp, st.st_size)) {
389 if (nomove || priv_move_log()) {
391 "Invalid/incompatible log file, move it away");
406 scan_dump(FILE *fp, off_t size)
408 struct pcap_file_header hdr;
410 struct pcap_sf_pkthdr ph;
412 struct pcap_pkthdr ph;
417 * Must read the file, compare the header against our new
418 * options (in particular, snaplen) and adjust our options so
419 * that we generate a correct file. Furthermore, check the file
420 * for consistency so that we can append safely.
422 * XXX this may take a long time for large logs.
424 (void) fseek(fp, 0L, SEEK_SET);
426 if (fread((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
427 logmsg(LOG_ERR, "Short file header");
431 if (hdr.magic != TCPDUMP_MAGIC ||
432 hdr.version_major != PCAP_VERSION_MAJOR ||
433 hdr.version_minor != PCAP_VERSION_MINOR ||
434 hdr.linktype != hpcap->linktype ||
435 hdr.snaplen > PFLOGD_MAXSNAPLEN) {
442 off_t len = fread((char *)&ph, 1, sizeof(ph), fp);
446 if (len != sizeof(ph))
448 if (ph.caplen > hdr.snaplen || ph.caplen > PFLOGD_MAXSNAPLEN)
450 pos += sizeof(ph) + ph.caplen;
453 fseek(fp, ph.caplen, SEEK_CUR);
459 if (hdr.snaplen != cur_snaplen) {
461 "Existing file has different snaplen %u, using it",
463 if (set_snaplen(hdr.snaplen)) {
465 "Failed, using old settings, offset %llu",
466 (unsigned long long) size);
473 logmsg(LOG_ERR, "Corrupted log file.");
477 /* dump a packet directly to the stream, which is unbuffered */
479 dump_packet_nobuf(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
481 FILE *f = (FILE *)user;
483 struct pcap_sf_pkthdr sh;
492 sh.ts.tv_sec = (bpf_int32)h->ts.tv_sec;
493 sh.ts.tv_usec = (bpf_int32)h->ts.tv_usec;
494 sh.caplen = h->caplen;
497 if (fwrite((char *)&sh, sizeof(sh), 1, f) != 1) {
499 if (fwrite((char *)h, sizeof(*h), 1, f) != 1) {
501 off_t pos = ftello(f);
503 /* try to undo header to prevent corruption */
505 if (pos < sizeof(sh) ||
506 ftruncate(fileno(f), pos - sizeof(sh))) {
508 if (pos < sizeof(*h) ||
509 ftruncate(fileno(f), pos - sizeof(*h))) {
511 logmsg(LOG_ERR, "Write failed, corrupted logfile!");
519 if (fwrite((char *)sp, h->caplen, 1, f) != 1)
527 logmsg(LOG_ERR, "Logging suspended: fwrite: %s", strerror(errno));
531 flush_buffer(FILE *f)
534 int len = bufpos - buffer;
540 if (offset == (off_t)-1) {
542 logmsg(LOG_ERR, "Logging suspended: ftello: %s",
547 if (fwrite(buffer, len, 1, f) != 1) {
549 logmsg(LOG_ERR, "Logging suspended: fwrite: %s",
551 ftruncate(fileno(f), offset);
566 packets_dropped += bufpkt;
574 /* append packet to the buffer, flushing if necessary */
576 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
578 FILE *f = (FILE *)user;
580 struct pcap_sf_pkthdr sh;
581 size_t len = sizeof(sh) + h->caplen;
583 size_t len = sizeof(*h) + h->caplen;
586 if (len < sizeof(*h) || h->caplen > (size_t)cur_snaplen) {
587 logmsg(LOG_NOTICE, "invalid size %u (%u/%u), packet dropped",
588 len, cur_snaplen, snaplen);
601 if (flush_buffer(f)) {
607 dump_packet_nobuf(user, h, sp);
613 sh.ts.tv_sec = (bpf_int32)h->ts.tv_sec;
614 sh.ts.tv_usec = (bpf_int32)h->ts.tv_usec;
615 sh.caplen = h->caplen;
618 memcpy(bufpos, &sh, sizeof(sh));
619 memcpy(bufpos + sizeof(sh), sp, h->caplen);
621 memcpy(bufpos, h, sizeof(*h));
622 memcpy(bufpos + sizeof(*h), sp, h->caplen);
635 struct pcap_stat pstat;
636 if (pcap_stats(hpcap, &pstat) < 0)
637 logmsg(LOG_WARNING, "Reading stats: %s", pcap_geterr(hpcap));
640 "%u packets received, %u/%u dropped (kernel/pflogd)",
641 pstat.ps_recv, pstat.ps_drop, packets_dropped);
645 main(int argc, char **argv)
647 int ch, np, ret, Xflag = 0;
648 pcap_handler phandler = dump_packet;
649 const char *errstr = NULL;
654 closefrom(STDERR_FILENO + 1);
656 while ((ch = getopt(argc, argv, "Dxd:f:i:p:s:")) != -1) {
662 delay = strtonum(optarg, 5, 60*60, &errstr);
676 snaplen = strtonum(optarg, 0, PFLOGD_MAXSNAPLEN,
679 snaplen = DEF_SNAPLEN;
681 snaplen = PFLOGD_MAXSNAPLEN;
696 /* does interface exist */
697 if (!if_exists(interface)) {
698 warn("Failed to initialize: %s", interface);
699 logmsg(LOG_ERR, "Failed to initialize: %s", interface);
700 logmsg(LOG_ERR, "Exiting, init failure");
705 openlog("pflogd", LOG_PID | LOG_CONS, LOG_DAEMON);
707 logmsg(LOG_WARNING, "Failed to become daemon: %s",
714 (void)umask(S_IRWXG | S_IRWXO);
716 /* filter will be used by the privileged process */
718 filter = copy_argv(argv);
720 logmsg(LOG_NOTICE, "Failed to form filter expression");
723 /* initialize pcap before dropping privileges */
725 logmsg(LOG_ERR, "Exiting, init failure");
729 /* Privilege separation begins here */
731 logmsg(LOG_ERR, "unable to privsep");
735 setproctitle("[initializing]");
736 /* Process is now unprivileged and inside a chroot */
737 signal(SIGTERM, sig_close);
738 signal(SIGINT, sig_close);
739 signal(SIGQUIT, sig_close);
740 signal(SIGALRM, sig_alrm);
741 signal(SIGUSR1, sig_usr1);
742 signal(SIGHUP, sig_hup);
745 buffer = malloc(PFLOGD_BUFSIZE);
747 if (buffer == NULL) {
748 logmsg(LOG_WARNING, "Failed to allocate output buffer");
749 phandler = dump_packet_nobuf;
751 bufleft = buflen = PFLOGD_BUFSIZE;
756 if (reset_dump(Xflag) < 0) {
760 logmsg(LOG_ERR, "Logging suspended: open error");
766 np = pcap_dispatch(hpcap, PCAP_NUM_PKTS,
767 phandler, (u_char *)dpcap);
769 if (!if_exists(interface) == -1) {
770 logmsg(LOG_NOTICE, "interface %s went away",
775 logmsg(LOG_NOTICE, "%s", pcap_geterr(hpcap));
783 "Logging suspended: open error");
804 logmsg(LOG_NOTICE, "Exiting");