1 /* $NetBSD: pflogd.c,v 1.6 2009/07/15 18:05:17 christos Exp $ */
2 /* $OpenBSD: pflogd.c,v 1.45 2007/06/06 14:11:26 henning Exp $ */
5 * Copyright (c) 2001 Theo de Raadt
6 * Copyright (c) 2001 Can Erkin Acar
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * - Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * - Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer in the documentation and/or other materials provided
18 * with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 * POSSIBILITY OF SUCH DAMAGE.
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
38 #include <sys/socket.h>
45 * If we're going to include parts of the libpcap internals we MUST
46 * set the feature-test macros they expect, or they may misbehave.
50 #define HAVE_VSNPRINTF
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 *);
84 int if_exists(char *);
86 void logmsg(int, const char *, ...);
87 void purge_buffer(void);
89 int scan_dump(FILE *, off_t
);
91 void set_suspended(int);
97 static int try_reset_dump(int);
99 /* buffer must always be greater than snaplen */
100 static int bufpkt
= 0; /* number of packets in buffer */
101 static int buflen
= 0; /* allocated size of buffer */
102 static char *buffer
= NULL
; /* packet buffer */
103 static char *bufpos
= NULL
; /* position in buffer */
104 static int bufleft
= 0; /* bytes left in buffer */
106 /* if error, stop logging but count dropped packets */
107 static int suspended
= -1;
108 static long packets_dropped
= 0;
117 setproctitle("[%s] -s %d -i %s -f %s",
118 suspended
? "suspended" : "running",
119 cur_snaplen
, interface
, filename
);
123 copy_argv(char * const *argv
)
131 for (n
= 0; argv
[n
]; n
++)
132 len
+= strlen(argv
[n
])+1;
140 strlcpy(buf
, argv
[0], len
);
141 for (n
= 1; argv
[n
]; n
++) {
142 strlcat(buf
, " ", len
);
143 strlcat(buf
, argv
[n
], len
);
149 logmsg(int pri
, const char *message
, ...)
152 va_start(ap
, message
);
155 vfprintf(stderr
, message
, ap
);
156 fprintf(stderr
, "\n");
158 vsyslog(pri
, message
, ap
);
165 fprintf(stderr
, "usage: pflogd [-Dx] [-d delay] [-f filename]");
166 fprintf(stderr
, " [-i interface] [-p pidfile]\n");
167 fprintf(stderr
, " [-s snaplen] [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
);
204 if_exists(char *ifname
)
208 struct ifdatareq ifr
;
209 #define ifr_name ifdr_name
212 struct if_data ifrdat
;
215 if ((s
= socket(AF_INET
, SOCK_DGRAM
, 0)) == -1)
217 bzero(&ifr
, sizeof(ifr
));
218 if (strlcpy(ifr
.ifr_name
, ifname
, sizeof(ifr
.ifr_name
)) >=
219 sizeof(ifr
.ifr_name
))
220 errx(1, "main ifr_name: strlcpy");
222 ifr
.ifr_data
= (caddr_t
)&ifrdat
;
224 if (ioctl(s
, SIOCGIFDATA
, (caddr_t
)&ifr
) == -1)
235 hpcap
= pcap_open_live(interface
, snaplen
, 1, PCAP_TO_MS
, errbuf
);
237 logmsg(LOG_ERR
, "Failed to initialize: %s", errbuf
);
241 if (pcap_datalink(hpcap
) != DLT_PFLOG
) {
242 logmsg(LOG_ERR
, "Invalid datalink type");
250 cur_snaplen
= snaplen
= pcap_snapshot(hpcap
);
254 if (ioctl(pcap_fileno(hpcap
), BIOCLOCK
) < 0) {
255 logmsg(LOG_ERR
, "BIOCLOCK: %s", strerror(errno
));
264 set_snaplen(int snap
)
266 if (priv_set_snaplen(snap
))
269 if (cur_snaplen
> snap
)
278 reset_dump(int nomove
)
283 ret
= try_reset_dump(nomove
);
292 * tries to (re)open log file, nomove flag is used with -x switch
293 * returns 0: success, 1: retry (log moved), -1: error
296 try_reset_dump(int nomove
)
298 struct pcap_file_header hdr
;
313 * Basically reimplement pcap_dump_open() because it truncates
314 * files and duplicates headers and such.
316 fd
= priv_open_log();
320 fp
= fdopen(fd
, "a+");
323 logmsg(LOG_ERR
, "Error: %s: %s", filename
, strerror(errno
));
327 if (fstat(fileno(fp
), &st
) == -1) {
328 logmsg(LOG_ERR
, "Error: %s: %s", filename
, strerror(errno
));
333 /* set FILE unbuffered, we do our own buffering */
334 if (setvbuf(fp
, NULL
, _IONBF
, 0)) {
335 logmsg(LOG_ERR
, "Failed to set output buffers");
340 #define TCPDUMP_MAGIC 0xa1b2c3d4
342 if (st
.st_size
== 0) {
343 if (snaplen
!= cur_snaplen
) {
344 logmsg(LOG_NOTICE
, "Using snaplen %d", snaplen
);
345 if (set_snaplen(snaplen
))
347 "Failed, using old settings");
349 hdr
.magic
= TCPDUMP_MAGIC
;
350 hdr
.version_major
= PCAP_VERSION_MAJOR
;
351 hdr
.version_minor
= PCAP_VERSION_MINOR
;
352 hdr
.thiszone
= hpcap
->tzoff
;
353 hdr
.snaplen
= hpcap
->snapshot
;
355 hdr
.linktype
= hpcap
->linktype
;
357 if (fwrite((char *)&hdr
, sizeof(hdr
), 1, fp
) != 1) {
361 } else if (scan_dump(fp
, st
.st_size
)) {
363 if (nomove
|| priv_move_log()) {
365 "Invalid/incompatible log file, move it away");
380 scan_dump(FILE *fp
, off_t size
)
382 struct pcap_file_header hdr
;
384 struct pcap_pkthdr ph
;
386 struct pcap_sf_pkthdr ph
;
391 * Must read the file, compare the header against our new
392 * options (in particular, snaplen) and adjust our options so
393 * that we generate a correct file. Furthermore, check the file
394 * for consistency so that we can append safely.
396 * XXX this may take a long time for large logs.
398 (void) fseek(fp
, 0L, SEEK_SET
);
400 if (fread((char *)&hdr
, sizeof(hdr
), 1, fp
) != 1) {
401 logmsg(LOG_ERR
, "Short file header");
405 if (hdr
.magic
!= TCPDUMP_MAGIC
||
406 hdr
.version_major
!= PCAP_VERSION_MAJOR
||
407 hdr
.version_minor
!= PCAP_VERSION_MINOR
||
408 hdr
.linktype
!= hpcap
->linktype
||
409 hdr
.snaplen
> PFLOGD_MAXSNAPLEN
) {
416 off_t len
= fread((char *)&ph
, 1, sizeof(ph
), fp
);
420 if (len
!= sizeof(ph
))
422 if (ph
.caplen
> hdr
.snaplen
|| ph
.caplen
> PFLOGD_MAXSNAPLEN
)
424 pos
+= sizeof(ph
) + ph
.caplen
;
427 fseek(fp
, ph
.caplen
, SEEK_CUR
);
433 if (hdr
.snaplen
!= cur_snaplen
) {
435 "Existing file has different snaplen %u, using it",
437 if (set_snaplen(hdr
.snaplen
)) {
439 "Failed, using old settings, offset %llu",
440 (unsigned long long) size
);
447 logmsg(LOG_ERR
, "Corrupted log file.");
451 /* dump a packet directly to the stream, which is unbuffered */
453 dump_packet_nobuf(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
456 struct pcap_sf_pkthdr sf_hdr
;
458 FILE *f
= (FILE *)user
;
466 sf_hdr
.ts
.tv_sec
= h
->ts
.tv_sec
;
467 sf_hdr
.ts
.tv_usec
= h
->ts
.tv_usec
;
468 sf_hdr
.caplen
= h
->caplen
;
473 if (fwrite((char *)h
, sizeof(*h
), 1, f
) != 1) {
475 if (fwrite(&sf_hdr
, sizeof(sf_hdr
), 1, f
) != 1) {
477 /* try to undo header to prevent corruption */
478 off_t pos
= ftello(f
);
480 if (pos
< sizeof(*h
) ||
481 ftruncate(fileno(f
), pos
- sizeof(*h
))) {
483 if (pos
< sizeof(sf_hdr
) ||
484 ftruncate(fileno(f
), pos
- sizeof(sf_hdr
))) {
486 logmsg(LOG_ERR
, "Write failed, corrupted logfile!");
494 if (fwrite((char *)sp
, h
->caplen
, 1, f
) != 1)
502 logmsg(LOG_ERR
, "Logging suspended: fwrite: %s", strerror(errno
));
506 flush_buffer(FILE *f
)
509 int len
= bufpos
- buffer
;
515 if (offset
== (off_t
)-1) {
517 logmsg(LOG_ERR
, "Logging suspended: ftello: %s",
522 if (fwrite(buffer
, len
, 1, f
) != 1) {
524 logmsg(LOG_ERR
, "Logging suspended: fwrite: %s",
526 ftruncate(fileno(f
), offset
);
541 packets_dropped
+= bufpkt
;
549 /* append packet to the buffer, flushing if necessary */
551 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
553 FILE *f
= (FILE *)user
;
555 size_t len
= sizeof(*h
) + h
->caplen
;
557 struct pcap_sf_pkthdr sf_hdr
;
558 size_t len
= sizeof(sf_hdr
) + h
->caplen
;
561 if (len
< sizeof(*h
) || h
->caplen
> (size_t)cur_snaplen
) {
562 logmsg(LOG_NOTICE
, "invalid size %u (%u/%u), packet dropped",
563 len
, cur_snaplen
, snaplen
);
576 if (flush_buffer(f
)) {
582 dump_packet_nobuf(user
, h
, sp
);
588 memcpy(bufpos
, h
, sizeof(*h
));
589 memcpy(bufpos
+ sizeof(*h
), sp
, h
->caplen
);
591 sf_hdr
.ts
.tv_sec
= h
->ts
.tv_sec
;
592 sf_hdr
.ts
.tv_usec
= h
->ts
.tv_usec
;
593 sf_hdr
.caplen
= h
->caplen
;
596 memcpy(bufpos
, &sf_hdr
, sizeof(sf_hdr
));
597 memcpy(bufpos
+ sizeof(sf_hdr
), sp
, h
->caplen
);
608 main(int argc
, char **argv
)
610 struct pcap_stat pstat
;
611 int ch
, np
, ret
, Xflag
= 0;
612 pcap_handler phandler
= dump_packet
;
613 const char *errstr
= NULL
;
618 closefrom(STDERR_FILENO
+ 1);
620 while ((ch
= getopt(argc
, argv
, "Dxd:f:i:p:s:")) != -1) {
626 delay
= strtonum(optarg
, 5, 60*60, &errstr
);
640 snaplen
= strtonum(optarg
, 0, PFLOGD_MAXSNAPLEN
,
643 snaplen
= DEF_SNAPLEN
;
645 snaplen
= PFLOGD_MAXSNAPLEN
;
660 /* does interface exist */
661 if (!if_exists(interface
)) {
662 warn("Failed to initialize: %s", interface
);
663 logmsg(LOG_ERR
, "Failed to initialize: %s", interface
);
664 logmsg(LOG_ERR
, "Exiting, init failure");
669 openlog("pflogd", LOG_PID
| LOG_CONS
, LOG_DAEMON
);
671 logmsg(LOG_WARNING
, "Failed to become daemon: %s",
678 (void)umask(S_IRWXG
| S_IRWXO
);
680 /* filter will be used by the privileged process */
682 filter
= copy_argv(argv
);
684 logmsg(LOG_NOTICE
, "Failed to form filter expression");
687 /* initialize pcap before dropping privileges */
689 logmsg(LOG_ERR
, "Exiting, init failure");
693 /* Privilege separation begins here */
695 logmsg(LOG_ERR
, "unable to privsep");
699 setproctitle("[initializing]");
700 /* Process is now unprivileged and inside a chroot */
701 signal(SIGTERM
, sig_close
);
702 signal(SIGINT
, sig_close
);
703 signal(SIGQUIT
, sig_close
);
704 signal(SIGALRM
, sig_alrm
);
705 signal(SIGHUP
, sig_hup
);
708 buffer
= malloc(PFLOGD_BUFSIZE
);
710 if (buffer
== NULL
) {
711 logmsg(LOG_WARNING
, "Failed to allocate output buffer");
712 phandler
= dump_packet_nobuf
;
714 bufleft
= buflen
= PFLOGD_BUFSIZE
;
719 if (reset_dump(Xflag
) < 0) {
723 logmsg(LOG_ERR
, "Logging suspended: open error");
729 np
= pcap_dispatch(hpcap
, PCAP_NUM_PKTS
,
730 phandler
, (u_char
*)dpcap
);
732 if (!if_exists(interface
) == -1) {
733 logmsg(LOG_NOTICE
, "interface %s went away",
738 logmsg(LOG_NOTICE
, "%s", pcap_geterr(hpcap
));
746 "Logging suspended: open error");
762 logmsg(LOG_NOTICE
, "Exiting");
769 if (pcap_stats(hpcap
, &pstat
) < 0)
770 logmsg(LOG_WARNING
, "Reading stats: %s", pcap_geterr(hpcap
));
773 "%u packets received, %u/%u dropped (kernel/pflogd)",
774 pstat
.ps_recv
, pstat
.ps_drop
, packets_dropped
);