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>
63 static int snaplen = DEF_SNAPLEN;
64 static int cur_snaplen = DEF_SNAPLEN;
66 volatile sig_atomic_t gotsig_close, gotsig_alrm, gotsig_hup;
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 int flush_buffer(FILE *);
82 void logmsg(int, const char *, ...);
83 void purge_buffer(void);
85 int scan_dump(FILE *, off_t);
87 void set_suspended(int);
93 static int try_reset_dump(int);
95 /* buffer must always be greater than snaplen */
96 static int bufpkt = 0; /* number of packets in buffer */
97 static int buflen = 0; /* allocated size of buffer */
98 static char *buffer = NULL; /* packet buffer */
99 static char *bufpos = NULL; /* position in buffer */
100 static int bufleft = 0; /* bytes left in buffer */
102 /* if error, stop logging but count dropped packets */
103 static int suspended = -1;
104 static long packets_dropped = 0;
113 setproctitle("[%s] -s %d -i %s -f %s",
114 suspended ? "suspended" : "running",
115 cur_snaplen, interface, filename);
119 copy_argv(char * const *argv)
127 for (n = 0; argv[n]; n++)
128 len += strlen(argv[n])+1;
136 strlcpy(buf, argv[0], len);
137 for (n = 1; argv[n]; n++) {
138 strlcat(buf, " ", len);
139 strlcat(buf, argv[n], len);
145 logmsg(int pri, const char *message, ...)
148 va_start(ap, message);
151 vfprintf(stderr, message, ap);
152 fprintf(stderr, "\n");
154 vsyslog(pri, message, ap);
165 fprintf(stderr, "usage: pflogd [-Dx] [-d delay] [-f filename]");
166 fprintf(stderr, " [-i interface] [-s snaplen]\n");
167 fprintf(stderr, " [expression]\n");
190 set_pcap_filter(void)
192 struct bpf_program bprog;
194 if (pcap_compile(hpcap, &bprog, filter, PCAP_OPT_FIL, 0) < 0)
195 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
197 if (pcap_setfilter(hpcap, &bprog) < 0)
198 logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
199 pcap_freecode(&bprog);
206 hpcap = pcap_open_live(interface, snaplen, 1, PCAP_TO_MS, errbuf);
208 logmsg(LOG_ERR, "Failed to initialize: %s", errbuf);
212 if (pcap_datalink(hpcap) != DLT_PFLOG) {
213 logmsg(LOG_ERR, "Invalid datalink type");
221 cur_snaplen = snaplen = pcap_snapshot(hpcap);
224 if (ioctl(pcap_fileno(hpcap), BIOCLOCK) < 0) {
225 logmsg(LOG_ERR, "BIOCLOCK: %s", strerror(errno));
233 set_snaplen(int snap)
235 if (priv_set_snaplen(snap))
238 if (cur_snaplen > snap)
247 reset_dump(int nomove)
252 ret = try_reset_dump(nomove);
261 * tries to (re)open log file, nomove flag is used with -x switch
262 * returns 0: success, 1: retry (log moved), -1: error
265 try_reset_dump(int nomove)
267 struct pcap_file_header hdr;
282 * Basically reimplement pcap_dump_open() because it truncates
283 * files and duplicates headers and such.
285 fd = priv_open_log();
289 fp = fdopen(fd, "a+");
292 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
296 if (fstat(fileno(fp), &st) == -1) {
297 logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
302 /* set FILE unbuffered, we do our own buffering */
303 if (setvbuf(fp, NULL, _IONBF, 0)) {
304 logmsg(LOG_ERR, "Failed to set output buffers");
309 #define TCPDUMP_MAGIC 0xa1b2c3d4
311 if (st.st_size == 0) {
312 if (snaplen != cur_snaplen) {
313 logmsg(LOG_NOTICE, "Using snaplen %d", snaplen);
314 if (set_snaplen(snaplen))
316 "Failed, using old settings");
318 hdr.magic = TCPDUMP_MAGIC;
319 hdr.version_major = PCAP_VERSION_MAJOR;
320 hdr.version_minor = PCAP_VERSION_MINOR;
321 hdr.thiszone = hpcap->tzoff;
322 hdr.snaplen = hpcap->snapshot;
324 hdr.linktype = hpcap->linktype;
326 if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
330 } else if (scan_dump(fp, st.st_size)) {
332 if (nomove || priv_move_log()) {
334 "Invalid/incompatible log file, move it away");
349 scan_dump(FILE *fp, off_t size)
351 struct pcap_file_header hdr;
353 struct pcap_sf_pkthdr ph;
355 struct pcap_pkthdr ph;
360 * Must read the file, compare the header against our new
361 * options (in particular, snaplen) and adjust our options so
362 * that we generate a correct file. Furthermore, check the file
363 * for consistency so that we can append safely.
365 * XXX this may take a long time for large logs.
367 (void) fseek(fp, 0L, SEEK_SET);
369 if (fread((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
370 logmsg(LOG_ERR, "Short file header");
374 if (hdr.magic != TCPDUMP_MAGIC ||
375 hdr.version_major != PCAP_VERSION_MAJOR ||
376 hdr.version_minor != PCAP_VERSION_MINOR ||
377 hdr.linktype != hpcap->linktype ||
378 hdr.snaplen > PFLOGD_MAXSNAPLEN) {
385 off_t len = fread((char *)&ph, 1, sizeof(ph), fp);
389 if (len != sizeof(ph))
391 if (ph.caplen > hdr.snaplen || ph.caplen > PFLOGD_MAXSNAPLEN)
393 pos += sizeof(ph) + ph.caplen;
396 fseek(fp, ph.caplen, SEEK_CUR);
402 if (hdr.snaplen != cur_snaplen) {
404 "Existing file has different snaplen %u, using it",
406 if (set_snaplen(hdr.snaplen)) {
408 "Failed, using old settings, offset %llu",
409 (unsigned long long) size);
416 logmsg(LOG_ERR, "Corrupted log file.");
420 /* dump a packet directly to the stream, which is unbuffered */
422 dump_packet_nobuf(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
424 FILE *f = (FILE *)user;
426 struct pcap_sf_pkthdr sh;
435 sh.ts.tv_sec = (bpf_int32)h->ts.tv_sec;
436 sh.ts.tv_usec = (bpf_int32)h->ts.tv_usec;
437 sh.caplen = h->caplen;
440 if (fwrite((char *)&sh, sizeof(sh), 1, f) != 1) {
442 if (fwrite((char *)h, sizeof(*h), 1, f) != 1) {
444 off_t pos = ftello(f);
446 /* try to undo header to prevent corruption */
448 if (pos < sizeof(sh) ||
449 ftruncate(fileno(f), pos - sizeof(sh))) {
451 if (pos < sizeof(*h) ||
452 ftruncate(fileno(f), pos - sizeof(*h))) {
454 logmsg(LOG_ERR, "Write failed, corrupted logfile!");
462 if (fwrite((char *)sp, h->caplen, 1, f) != 1)
470 logmsg(LOG_ERR, "Logging suspended: fwrite: %s", strerror(errno));
474 flush_buffer(FILE *f)
477 int len = bufpos - buffer;
483 if (offset == (off_t)-1) {
485 logmsg(LOG_ERR, "Logging suspended: ftello: %s",
490 if (fwrite(buffer, len, 1, f) != 1) {
492 logmsg(LOG_ERR, "Logging suspended: fwrite: %s",
494 ftruncate(fileno(f), offset);
509 packets_dropped += bufpkt;
517 /* append packet to the buffer, flushing if necessary */
519 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
521 FILE *f = (FILE *)user;
523 struct pcap_sf_pkthdr sh;
524 size_t len = sizeof(sh) + h->caplen;
526 size_t len = sizeof(*h) + h->caplen;
529 if (len < sizeof(*h) || h->caplen > (size_t)cur_snaplen) {
530 logmsg(LOG_NOTICE, "invalid size %u (%u/%u), packet dropped",
531 len, cur_snaplen, snaplen);
544 if (flush_buffer(f)) {
550 dump_packet_nobuf(user, h, sp);
556 sh.ts.tv_sec = (bpf_int32)h->ts.tv_sec;
557 sh.ts.tv_usec = (bpf_int32)h->ts.tv_usec;
558 sh.caplen = h->caplen;
561 memcpy(bufpos, &sh, sizeof(sh));
562 memcpy(bufpos + sizeof(sh), sp, h->caplen);
564 memcpy(bufpos, h, sizeof(*h));
565 memcpy(bufpos + sizeof(*h), sp, h->caplen);
576 main(int argc, char **argv)
578 struct pcap_stat pstat;
579 int ch, np, Xflag = 0;
580 pcap_handler phandler = dump_packet;
581 const char *errstr = NULL;
584 /* another ?paranoid? safety measure we do not have */
586 closefrom(STDERR_FILENO + 1);
589 while ((ch = getopt(argc, argv, "Dxd:f:i:s:")) != -1) {
595 delay = strtonum(optarg, 5, 60*60, &errstr);
606 snaplen = strtonum(optarg, 0, PFLOGD_MAXSNAPLEN,
609 snaplen = DEF_SNAPLEN;
611 snaplen = PFLOGD_MAXSNAPLEN;
627 openlog("pflogd", LOG_PID | LOG_CONS, LOG_DAEMON);
629 logmsg(LOG_WARNING, "Failed to become daemon: %s",
636 (void)umask(S_IRWXG | S_IRWXO);
638 /* filter will be used by the privileged process */
640 filter = copy_argv(argv);
642 logmsg(LOG_NOTICE, "Failed to form filter expression");
645 /* initialize pcap before dropping privileges */
647 logmsg(LOG_ERR, "Exiting, init failure");
651 /* Privilege separation begins here */
653 logmsg(LOG_ERR, "unable to privsep");
657 setproctitle("[initializing]");
658 /* Process is now unprivileged and inside a chroot */
659 signal(SIGTERM, sig_close);
660 signal(SIGINT, sig_close);
661 signal(SIGQUIT, sig_close);
662 signal(SIGALRM, sig_alrm);
663 signal(SIGHUP, sig_hup);
666 buffer = malloc(PFLOGD_BUFSIZE);
668 if (buffer == NULL) {
669 logmsg(LOG_WARNING, "Failed to allocate output buffer");
670 phandler = dump_packet_nobuf;
672 bufleft = buflen = PFLOGD_BUFSIZE;
677 if (reset_dump(Xflag) < 0) {
681 logmsg(LOG_ERR, "Logging suspended: open error");
687 np = pcap_dispatch(hpcap, PCAP_NUM_PKTS,
688 phandler, (u_char *)dpcap);
691 if (errno == ENXIO) {
693 "Device not/no longer configured");
697 logmsg(LOG_NOTICE, "%s", pcap_geterr(hpcap));
705 "Logging suspended: open error");
721 logmsg(LOG_NOTICE, "Exiting");
728 if (pcap_stats(hpcap, &pstat) < 0)
729 logmsg(LOG_WARNING, "Reading stats: %s", pcap_geterr(hpcap));
732 "%u packets received, %u/%u dropped (kernel/pflogd)",
733 pstat.ps_recv, pstat.ps_drop, packets_dropped);