1 /* $OpenBSD: pflogd.c,v 1.37 2006/10/26 13:34:47 jmc 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>
41 #include <net/bpf.h> /* BIOCLOCK */
66 static int snaplen = DEF_SNAPLEN;
67 static int cur_snaplen = DEF_SNAPLEN;
69 volatile sig_atomic_t gotsig_close, gotsig_alrm, gotsig_hup;
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 int flush_buffer(FILE *);
85 void logmsg(int, const char *, ...);
86 void purge_buffer(void);
88 int scan_dump(FILE *, off_t);
90 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] [-s snaplen]\n");
170 fprintf(stderr, " [expression]\n");
193 set_pcap_filter(void)
195 struct bpf_program bprog;
197 if (pcap_compile(hpcap, &bprog, filter, PCAP_OPT_FIL, 0) < 0)
198 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
200 if (pcap_setfilter(hpcap, &bprog) < 0)
201 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
202 pcap_freecode(&bprog);
209 hpcap = pcap_open_live(interface, snaplen, 1, PCAP_TO_MS, errbuf);
211 logmsg(LOG_ERR, "Failed to initialize: %s", errbuf);
215 if (pcap_datalink(hpcap) != DLT_PFLOG) {
216 logmsg(LOG_ERR, "Invalid datalink type");
224 cur_snaplen = snaplen = pcap_snapshot(hpcap);
227 if (ioctl(pcap_fileno(hpcap), BIOCLOCK) < 0) {
228 logmsg(LOG_ERR, "BIOCLOCK: %s", strerror(errno));
236 set_snaplen(int snap)
238 if (priv_set_snaplen(snap))
241 if (cur_snaplen > snap)
250 reset_dump(int nomove)
255 ret = try_reset_dump(nomove);
264 * tries to (re)open log file, nomove flag is used with -x switch
265 * returns 0: success, 1: retry (log moved), -1: error
268 try_reset_dump(int nomove)
270 struct pcap_file_header hdr;
285 * Basically reimplement pcap_dump_open() because it truncates
286 * files and duplicates headers and such.
288 fd = priv_open_log();
292 fp = fdopen(fd, "a+");
295 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
299 if (fstat(fileno(fp), &st) == -1) {
300 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
305 /* set FILE unbuffered, we do our own buffering */
306 if (setvbuf(fp, NULL, _IONBF, 0)) {
307 logmsg(LOG_ERR, "Failed to set output buffers");
312 #define TCPDUMP_MAGIC 0xa1b2c3d4
314 if (st.st_size == 0) {
315 if (snaplen != cur_snaplen) {
316 logmsg(LOG_NOTICE, "Using snaplen %d", snaplen);
317 if (set_snaplen(snaplen))
319 "Failed, using old settings");
321 hdr.magic = TCPDUMP_MAGIC;
322 hdr.version_major = PCAP_VERSION_MAJOR;
323 hdr.version_minor = PCAP_VERSION_MINOR;
324 hdr.thiszone = hpcap->tzoff;
325 hdr.snaplen = hpcap->snapshot;
327 hdr.linktype = hpcap->linktype;
329 if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
333 } else if (scan_dump(fp, st.st_size)) {
335 if (nomove || priv_move_log()) {
337 "Invalid/incompatible log file, move it away");
352 scan_dump(FILE *fp, off_t size)
354 struct pcap_file_header hdr;
356 struct pcap_sf_pkthdr ph;
358 struct pcap_pkthdr ph;
363 * Must read the file, compare the header against our new
364 * options (in particular, snaplen) and adjust our options so
365 * that we generate a correct file. Furthermore, check the file
366 * for consistency so that we can append safely.
368 * XXX this may take a long time for large logs.
370 (void) fseek(fp, 0L, SEEK_SET);
372 if (fread((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
373 logmsg(LOG_ERR, "Short file header");
377 if (hdr.magic != TCPDUMP_MAGIC ||
378 hdr.version_major != PCAP_VERSION_MAJOR ||
379 hdr.version_minor != PCAP_VERSION_MINOR ||
380 hdr.linktype != hpcap->linktype ||
381 hdr.snaplen > PFLOGD_MAXSNAPLEN) {
388 off_t len = fread((char *)&ph, 1, sizeof(ph), fp);
392 if (len != sizeof(ph))
394 if (ph.caplen > hdr.snaplen || ph.caplen > PFLOGD_MAXSNAPLEN)
396 pos += sizeof(ph) + ph.caplen;
399 fseek(fp, ph.caplen, SEEK_CUR);
405 if (hdr.snaplen != cur_snaplen) {
407 "Existing file has different snaplen %u, using it",
409 if (set_snaplen(hdr.snaplen)) {
411 "Failed, using old settings, offset %llu",
412 (unsigned long long) size);
419 logmsg(LOG_ERR, "Corrupted log file.");
423 /* dump a packet directly to the stream, which is unbuffered */
425 dump_packet_nobuf(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
427 FILE *f = (FILE *)user;
429 struct pcap_sf_pkthdr sh;
438 sh.ts.tv_sec = (bpf_int32)h->ts.tv_sec;
439 sh.ts.tv_usec = (bpf_int32)h->ts.tv_usec;
440 sh.caplen = h->caplen;
443 if (fwrite((char *)&sh, sizeof(sh), 1, f) != 1) {
445 if (fwrite((char *)h, sizeof(*h), 1, f) != 1) {
447 off_t pos = ftello(f);
449 /* try to undo header to prevent corruption */
451 if (pos < sizeof(sh) ||
452 ftruncate(fileno(f), pos - sizeof(sh))) {
454 if (pos < sizeof(*h) ||
455 ftruncate(fileno(f), pos - sizeof(*h))) {
457 logmsg(LOG_ERR, "Write failed, corrupted logfile!");
465 if (fwrite((char *)sp, h->caplen, 1, f) != 1)
473 logmsg(LOG_ERR, "Logging suspended: fwrite: %s", strerror(errno));
477 flush_buffer(FILE *f)
480 int len = bufpos - buffer;
486 if (offset == (off_t)-1) {
488 logmsg(LOG_ERR, "Logging suspended: ftello: %s",
493 if (fwrite(buffer, len, 1, f) != 1) {
495 logmsg(LOG_ERR, "Logging suspended: fwrite: %s",
497 ftruncate(fileno(f), offset);
512 packets_dropped += bufpkt;
520 /* append packet to the buffer, flushing if necessary */
522 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
524 FILE *f = (FILE *)user;
526 struct pcap_sf_pkthdr sh;
527 size_t len = sizeof(sh) + h->caplen;
529 size_t len = sizeof(*h) + h->caplen;
532 if (len < sizeof(*h) || h->caplen > (size_t)cur_snaplen) {
533 logmsg(LOG_NOTICE, "invalid size %u (%u/%u), packet dropped",
534 len, cur_snaplen, snaplen);
547 if (flush_buffer(f)) {
553 dump_packet_nobuf(user, h, sp);
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;
564 memcpy(bufpos, &sh, sizeof(sh));
565 memcpy(bufpos + sizeof(sh), sp, h->caplen);
567 memcpy(bufpos, h, sizeof(*h));
568 memcpy(bufpos + sizeof(*h), sp, h->caplen);
579 main(int argc, char **argv)
581 struct pcap_stat pstat;
582 int ch, np, Xflag = 0;
583 pcap_handler phandler = dump_packet;
584 const char *errstr = NULL;
587 /* another ?paranoid? safety measure we do not have */
589 closefrom(STDERR_FILENO + 1);
592 while ((ch = getopt(argc, argv, "Dxd:f:i:s:")) != -1) {
598 delay = strtonum(optarg, 5, 60*60, &errstr);
609 snaplen = strtonum(optarg, 0, PFLOGD_MAXSNAPLEN,
612 snaplen = DEF_SNAPLEN;
614 snaplen = PFLOGD_MAXSNAPLEN;
630 openlog("pflogd", LOG_PID | LOG_CONS, LOG_DAEMON);
632 logmsg(LOG_WARNING, "Failed to become daemon: %s",
639 (void)umask(S_IRWXG | S_IRWXO);
641 /* filter will be used by the privileged process */
643 filter = copy_argv(argv);
645 logmsg(LOG_NOTICE, "Failed to form filter expression");
648 /* initialize pcap before dropping privileges */
650 logmsg(LOG_ERR, "Exiting, init failure");
654 /* Privilege separation begins here */
656 logmsg(LOG_ERR, "unable to privsep");
660 setproctitle("[initializing]");
661 /* Process is now unprivileged and inside a chroot */
662 signal(SIGTERM, sig_close);
663 signal(SIGINT, sig_close);
664 signal(SIGQUIT, sig_close);
665 signal(SIGALRM, sig_alrm);
666 signal(SIGHUP, sig_hup);
669 buffer = malloc(PFLOGD_BUFSIZE);
671 if (buffer == NULL) {
672 logmsg(LOG_WARNING, "Failed to allocate output buffer");
673 phandler = dump_packet_nobuf;
675 bufleft = buflen = PFLOGD_BUFSIZE;
680 if (reset_dump(Xflag) < 0) {
684 logmsg(LOG_ERR, "Logging suspended: open error");
690 np = pcap_dispatch(hpcap, PCAP_NUM_PKTS,
691 phandler, (u_char *)dpcap);
694 if (errno == ENXIO) {
696 "Device not/no longer configured");
700 logmsg(LOG_NOTICE, "%s", pcap_geterr(hpcap));
708 "Logging suspended: open error");
724 logmsg(LOG_NOTICE, "Exiting");
731 if (pcap_stats(hpcap, &pstat) < 0)
732 logmsg(LOG_WARNING, "Reading stats: %s", pcap_geterr(hpcap));
735 "%u packets received, %u/%u dropped (kernel/pflogd)",
736 pstat.ps_recv, pstat.ps_drop, packets_dropped);