1 /* $OpenBSD: pflogd.c,v 1.45 2007/06/06 14:11:26 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>
61 static int snaplen
= DEF_SNAPLEN
;
62 static int cur_snaplen
= DEF_SNAPLEN
;
64 volatile sig_atomic_t gotsig_close
, gotsig_alrm
, gotsig_hup
, gotsig_usr1
;
66 const char *filename
= PFLOGD_LOG_FILE
;
67 const char *interface
= PFLOGD_DEFAULT_IF
;
70 char errbuf
[PCAP_ERRBUF_SIZE
];
73 unsigned int delay
= FLUSH_DELAY
;
75 char *copy_argv(char * const *);
76 void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
77 void dump_packet_nobuf(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
78 void log_pcap_stats(void);
79 int flush_buffer(FILE *);
80 int if_exists(char *);
82 void purge_buffer(void);
84 int scan_dump(FILE *, off_t
);
86 void set_suspended(int);
91 void usage(void) __dead2
;
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 size_t buflen
= 0; /* allocated size of buffer */
98 static char *buffer
= NULL
; /* packet buffer */
99 static char *bufpos
= NULL
; /* position in buffer */
100 static size_t 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
);
161 fprintf(stderr
, "usage: pflogd [-Dx] [-d delay] [-f filename]");
162 fprintf(stderr
, " [-i interface] [-p pidfile]\n");
163 fprintf(stderr
, " [-s snaplen] [expression]\n");
168 sig_close(int sig __unused
)
174 sig_hup(int sig __unused
)
180 sig_alrm(int sig __unused
)
186 sig_usr1(int sig __unused
)
192 set_pcap_filter(void)
194 struct bpf_program bprog
;
196 if (pcap_compile(hpcap
, &bprog
, filter
, PCAP_OPT_FIL
, 0) < 0)
197 logmsg(LOG_WARNING
, "%s", pcap_geterr(hpcap
));
199 if (pcap_setfilter(hpcap
, &bprog
) < 0)
200 logmsg(LOG_WARNING
, "%s", pcap_geterr(hpcap
));
201 pcap_freecode(&bprog
);
206 if_exists(char *ifname
)
210 struct if_data ifrdat
;
212 if ((s
= socket(AF_INET
, SOCK_DGRAM
, 0)) == -1)
214 bzero(&ifr
, sizeof(ifr
));
215 if (strlcpy(ifr
.ifr_name
, ifname
, sizeof(ifr
.ifr_name
)) >=
216 sizeof(ifr
.ifr_name
))
217 errx(1, "main ifr_name: strlcpy");
218 ifr
.ifr_data
= (caddr_t
)&ifrdat
;
219 if (ioctl(s
, SIOCGIFDATA
, (caddr_t
)&ifr
) == -1)
230 hpcap
= pcap_open_live(interface
, snaplen
, 1, PCAP_TO_MS
, errbuf
);
232 logmsg(LOG_ERR
, "Failed to initialize: %s", errbuf
);
236 if (pcap_datalink(hpcap
) != DLT_PFLOG
) {
237 logmsg(LOG_ERR
, "Invalid datalink type");
245 cur_snaplen
= snaplen
= pcap_snapshot(hpcap
);
247 /* From contrib/pf/pflogd.c 1.5 FreeBSD: BPF locking is not
250 #ifndef __DragonFly__
252 if (ioctl(pcap_fileno(hpcap
), BIOCLOCK
) < 0) {
253 logmsg(LOG_ERR
, "BIOCLOCK: %s", strerror(errno
));
262 set_snaplen(int snap
)
264 if (priv_set_snaplen(snap
))
267 if (cur_snaplen
> snap
)
276 reset_dump(int nomove
)
281 ret
= try_reset_dump(nomove
);
290 * tries to (re)open log file, nomove flag is used with -x switch
291 * returns 0: success, 1: retry (log moved), -1: error
294 try_reset_dump(int nomove
)
296 struct pcap_file_header hdr
;
311 * Basically reimplement pcap_dump_open() because it truncates
312 * files and duplicates headers and such.
314 fd
= priv_open_log();
318 fp
= fdopen(fd
, "a+");
321 logmsg(LOG_ERR
, "Error: %s: %s", filename
, strerror(errno
));
325 if (fstat(fileno(fp
), &st
) == -1) {
326 logmsg(LOG_ERR
, "Error: %s: %s", filename
, strerror(errno
));
331 /* set FILE unbuffered, we do our own buffering */
332 if (setvbuf(fp
, NULL
, _IONBF
, 0)) {
333 logmsg(LOG_ERR
, "Failed to set output buffers");
338 #define TCPDUMP_MAGIC 0xa1b2c3d4
340 if (st
.st_size
== 0) {
341 if (snaplen
!= cur_snaplen
) {
342 logmsg(LOG_NOTICE
, "Using snaplen %d", snaplen
);
343 if (set_snaplen(snaplen
))
345 "Failed, using old settings");
347 hdr
.magic
= TCPDUMP_MAGIC
;
348 hdr
.version_major
= PCAP_VERSION_MAJOR
;
349 hdr
.version_minor
= PCAP_VERSION_MINOR
;
350 /* https://www.tcpdump.org/manpages/pcap-savefile.5.txt */
352 hdr
.snaplen
= hpcap
->snapshot
;
354 hdr
.linktype
= hpcap
->linktype
;
356 if (fwrite((char *)&hdr
, sizeof(hdr
), 1, fp
) != 1) {
360 } else if (scan_dump(fp
, st
.st_size
)) {
362 if (nomove
|| priv_move_log()) {
364 "Invalid/incompatible log file, move it away");
379 scan_dump(FILE *fp
, off_t size
)
381 struct pcap_file_header hdr
;
382 struct pcap_sf_pkthdr ph
;
386 * Must read the file, compare the header against our new
387 * options (in particular, snaplen) and adjust our options so
388 * that we generate a correct file. Furthermore, check the file
389 * for consistency so that we can append safely.
391 * XXX this may take a long time for large logs.
393 fseek(fp
, 0L, SEEK_SET
);
395 if (fread((char *)&hdr
, sizeof(hdr
), 1, fp
) != 1) {
396 logmsg(LOG_ERR
, "Short file header");
400 if (hdr
.magic
!= TCPDUMP_MAGIC
||
401 hdr
.version_major
!= PCAP_VERSION_MAJOR
||
402 hdr
.version_minor
!= PCAP_VERSION_MINOR
||
403 (int)hdr
.linktype
!= hpcap
->linktype
||
404 hdr
.snaplen
> PFLOGD_MAXSNAPLEN
) {
411 off_t len
= fread((char *)&ph
, 1, sizeof(ph
), fp
);
415 if (len
!= sizeof(ph
))
417 if (ph
.caplen
> hdr
.snaplen
|| ph
.caplen
> PFLOGD_MAXSNAPLEN
)
419 pos
+= sizeof(ph
) + ph
.caplen
;
422 fseek(fp
, ph
.caplen
, SEEK_CUR
);
428 if ((int)hdr
.snaplen
!= cur_snaplen
) {
430 "Existing file has different snaplen %u, using it",
432 if (set_snaplen(hdr
.snaplen
)) {
434 "Failed, using old settings, offset %llu",
435 (unsigned long long) size
);
442 logmsg(LOG_ERR
, "Corrupted log file.");
446 /* dump a packet directly to the stream, which is unbuffered */
448 dump_packet_nobuf(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
450 FILE *f
= (FILE *)user
;
451 struct pcap_sf_pkthdr sh
;
458 sh
.ts
.tv_sec
= (bpf_int32
)h
->ts
.tv_sec
;
459 sh
.ts
.tv_usec
= (bpf_int32
)h
->ts
.tv_usec
;
460 sh
.caplen
= h
->caplen
;
463 if (fwrite((char *)&sh
, sizeof(sh
), 1, f
) != 1) {
464 off_t pos
= ftello(f
);
466 /* try to undo header to prevent corruption */
467 if ((size_t)pos
< sizeof(sh
) ||
468 ftruncate(fileno(f
), pos
- sizeof(sh
))) {
469 logmsg(LOG_ERR
, "Write failed, corrupted logfile!");
477 if (fwrite(sp
, h
->caplen
, 1, f
) != 1)
485 logmsg(LOG_ERR
, "Logging suspended: fwrite: %s", strerror(errno
));
489 flush_buffer(FILE *f
)
492 int len
= bufpos
- buffer
;
498 if (offset
== (off_t
)-1) {
500 logmsg(LOG_ERR
, "Logging suspended: ftello: %s",
505 if (fwrite(buffer
, len
, 1, f
) != 1) {
507 logmsg(LOG_ERR
, "Logging suspended: fwrite: %s",
509 ftruncate(fileno(f
), offset
);
524 packets_dropped
+= bufpkt
;
532 /* append packet to the buffer, flushing if necessary */
534 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
536 FILE *f
= (FILE *)user
;
537 struct pcap_sf_pkthdr sh
;
538 size_t len
= sizeof(sh
) + h
->caplen
;
540 if (len
< sizeof(*h
) || h
->caplen
> (size_t)cur_snaplen
) {
541 logmsg(LOG_NOTICE
, "invalid size %zd (%u/%u), packet dropped",
542 len
, cur_snaplen
, snaplen
);
555 if (flush_buffer(f
)) {
561 dump_packet_nobuf(user
, h
, sp
);
566 sh
.ts
.tv_sec
= (bpf_int32
)h
->ts
.tv_sec
;
567 sh
.ts
.tv_usec
= (bpf_int32
)h
->ts
.tv_usec
;
568 sh
.caplen
= h
->caplen
;
571 memcpy(bufpos
, &sh
, sizeof(sh
));
572 memcpy(bufpos
+ sizeof(sh
), sp
, h
->caplen
);
584 struct pcap_stat pstat
;
585 if (pcap_stats(hpcap
, &pstat
) < 0)
586 logmsg(LOG_WARNING
, "Reading stats: %s", pcap_geterr(hpcap
));
589 "%u packets received, %u/%ld dropped (kernel/pflogd)",
590 pstat
.ps_recv
, pstat
.ps_drop
, packets_dropped
);
594 main(int argc
, char **argv
)
596 int ch
, np
, ret
, Xflag
= 0;
597 pcap_handler phandler
= dump_packet
;
598 const char *errstr
= NULL
;
599 struct pidfh
*pfh
= NULL
;
604 /* Neither FreeBSD nor DFly have this; Max seems to think this may
605 * be a paranoid check. Comment it out:
606 closefrom(STDERR_FILENO + 1);
609 while ((ch
= getopt(argc
, argv
, "Dxd:f:i:p:s:")) != -1) {
615 delay
= strtonum(optarg
, 5, 60*60, &errstr
);
629 snaplen
= strtonum(optarg
, 0, PFLOGD_MAXSNAPLEN
,
632 snaplen
= DEF_SNAPLEN
;
634 snaplen
= PFLOGD_MAXSNAPLEN
;
649 /* does interface exist */
650 if (!if_exists(__DECONST(char *, interface
))) {
651 warn("Failed to initialize: %s", interface
);
652 logmsg(LOG_ERR
, "Failed to initialize: %s", interface
);
653 logmsg(LOG_ERR
, "Exiting, init failure");
658 openlog("pflogd", LOG_PID
| LOG_CONS
, LOG_DAEMON
);
659 pfh
= pidfile_open(pidf
, 0600, NULL
);
661 logmsg(LOG_WARNING
, "Failed to become daemon: %s",
668 umask(S_IRWXG
| S_IRWXO
);
670 /* filter will be used by the privileged process */
672 filter
= copy_argv(argv
);
674 logmsg(LOG_NOTICE
, "Failed to form filter expression");
677 /* initialize pcap before dropping privileges */
679 logmsg(LOG_ERR
, "Exiting, init failure");
683 /* Privilege separation begins here */
685 logmsg(LOG_ERR
, "unable to privsep");
689 setproctitle("[initializing]");
690 /* Process is now unprivileged and inside a chroot */
691 signal(SIGTERM
, sig_close
);
692 signal(SIGINT
, sig_close
);
693 signal(SIGQUIT
, sig_close
);
694 signal(SIGALRM
, sig_alrm
);
695 signal(SIGUSR1
, sig_usr1
);
696 signal(SIGHUP
, sig_hup
);
699 buffer
= malloc(PFLOGD_BUFSIZE
);
701 if (buffer
== NULL
) {
702 logmsg(LOG_WARNING
, "Failed to allocate output buffer");
703 phandler
= dump_packet_nobuf
;
705 bufleft
= buflen
= PFLOGD_BUFSIZE
;
710 if (reset_dump(Xflag
) < 0) {
714 logmsg(LOG_ERR
, "Logging suspended: open error");
720 np
= pcap_dispatch(hpcap
, PCAP_NUM_PKTS
,
721 phandler
, (u_char
*)dpcap
);
723 if (!if_exists(__DECONST(char *, interface
))) {
724 logmsg(LOG_NOTICE
, "interface %s went away",
729 logmsg(LOG_NOTICE
, "%s", pcap_geterr(hpcap
));
737 "Logging suspended: open error");
758 logmsg(LOG_NOTICE
, "Exiting");