xref: /dragonfly/usr.sbin/pflogd/pflogd.c (revision 926deccb)
1 /*	$OpenBSD: pflogd.c,v 1.45 2007/06/06 14:11:26 henning Exp $	*/
2 
3 /*
4  * Copyright (c) 2001 Theo de Raadt
5  * Copyright (c) 2001 Can Erkin Acar
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
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.
18  *
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.
31  */
32 
33 #include <sys/types.h>
34 #include <sys/ioctl.h>
35 #include <sys/file.h>
36 #include <sys/stat.h>
37 #include <sys/socket.h>
38 #include <net/if.h>
39 
40 #include <machine/inttypes.h>
41 
42 #include <errno.h>
43 #include <err.h>
44 #include <fcntl.h>
45 #include <syslog.h>
46 #include <signal.h>
47 #include <stdarg.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 
53 #include <libutil.h>
54 #include <pcap-int.h>
55 #include <pcap.h>
56 
57 #include "pflogd.h"
58 
59 pcap_t *hpcap;
60 static FILE *dpcap;
61 
62 int Debug = 0;
63 static int snaplen = DEF_SNAPLEN;
64 static int cur_snaplen = DEF_SNAPLEN;
65 
66 volatile sig_atomic_t gotsig_close, gotsig_alrm, gotsig_hup;
67 
68 const char *filename = PFLOGD_LOG_FILE;
69 const char *interface = PFLOGD_DEFAULT_IF;
70 char *filter = NULL;
71 
72 char errbuf[PCAP_ERRBUF_SIZE];
73 
74 int log_debug = 0;
75 unsigned int delay = FLUSH_DELAY;
76 
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 *);
81 int   if_exists(char *);
82 int   init_pcap(void);
83 void  purge_buffer(void);
84 int   reset_dump(int);
85 int   scan_dump(FILE *, off_t);
86 int   set_snaplen(int);
87 void  set_suspended(int);
88 void  sig_alrm(int);
89 void  sig_close(int);
90 void  sig_hup(int);
91 void  usage(void);
92 
93 static int try_reset_dump(int);
94 
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 */
101 
102 /* if error, stop logging but count dropped packets */
103 static int suspended = -1;
104 static long packets_dropped = 0;
105 
106 void
107 set_suspended(int s)
108 {
109 	if (suspended == s)
110 		return;
111 
112 	suspended = s;
113 	setproctitle("[%s] -s %d -i %s -f %s",
114 	    suspended ? "suspended" : "running",
115 	    cur_snaplen, interface, filename);
116 }
117 
118 char *
119 copy_argv(char * const *argv)
120 {
121 	size_t len = 0, n;
122 	char *buf;
123 
124 	if (argv == NULL)
125 		return (NULL);
126 
127 	for (n = 0; argv[n]; n++)
128 		len += strlen(argv[n])+1;
129 	if (len == 0)
130 		return (NULL);
131 
132 	buf = malloc(len);
133 	if (buf == NULL)
134 		return (NULL);
135 
136 	strlcpy(buf, argv[0], len);
137 	for (n = 1; argv[n]; n++) {
138 		strlcat(buf, " ", len);
139 		strlcat(buf, argv[n], len);
140 	}
141 	return (buf);
142 }
143 
144 void
145 logmsg(int pri, const char *message, ...)
146 {
147 	va_list ap;
148 	va_start(ap, message);
149 
150 	if (log_debug) {
151 		vfprintf(stderr, message, ap);
152 		fprintf(stderr, "\n");
153 	} else
154 		vsyslog(pri, message, ap);
155 	va_end(ap);
156 }
157 
158 void
159 usage(void)
160 {
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");
164 	exit(1);
165 }
166 
167 void
168 sig_close(int sig __unused)
169 {
170 	gotsig_close = 1;
171 }
172 
173 void
174 sig_hup(int sig __unused)
175 {
176 	gotsig_hup = 1;
177 }
178 
179 void
180 sig_alrm(int sig __unused)
181 {
182 	gotsig_alrm = 1;
183 }
184 
185 void
186 set_pcap_filter(void)
187 {
188 	struct bpf_program bprog;
189 
190 	if (pcap_compile(hpcap, &bprog, filter, PCAP_OPT_FIL, 0) < 0)
191 		logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
192 	else {
193 		if (pcap_setfilter(hpcap, &bprog) < 0)
194 			logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
195 		pcap_freecode(&bprog);
196 	}
197 }
198 
199 int
200 if_exists(char *ifname)
201 {
202 	int s;
203 	struct ifreq ifr;
204 	struct if_data ifrdat;
205 
206 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
207 		err(1, "socket");
208 	bzero(&ifr, sizeof(ifr));
209 	if (strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)) >=
210 		sizeof(ifr.ifr_name))
211 			errx(1, "main ifr_name: strlcpy");
212 	ifr.ifr_data = (caddr_t)&ifrdat;
213 	if (ioctl(s, SIOCGIFDATA, (caddr_t)&ifr) == -1)
214 		return (0);
215 	if (close(s))
216 		err(1, "close");
217 
218 	return (1);
219 }
220 
221 int
222 init_pcap(void)
223 {
224 	hpcap = pcap_open_live(interface, snaplen, 1, PCAP_TO_MS, errbuf);
225 	if (hpcap == NULL) {
226 		logmsg(LOG_ERR, "Failed to initialize: %s", errbuf);
227 		return (-1);
228 	}
229 
230 	if (pcap_datalink(hpcap) != DLT_PFLOG) {
231 		logmsg(LOG_ERR, "Invalid datalink type");
232 		pcap_close(hpcap);
233 		hpcap = NULL;
234 		return (-1);
235 	}
236 
237 	set_pcap_filter();
238 
239 	cur_snaplen = snaplen = pcap_snapshot(hpcap);
240 
241 	/* From contrib/pf/pflogd.c 1.5 FreeBSD: BPF locking is not
242 	 * (yet) supported.
243 	 */
244 	#ifndef __DragonFly__
245 	/* lock */
246 	if (ioctl(pcap_fileno(hpcap), BIOCLOCK) < 0) {
247 		logmsg(LOG_ERR, "BIOCLOCK: %s", strerror(errno));
248 		return (-1);
249 	}
250 	#endif
251 
252 	return (0);
253 }
254 
255 int
256 set_snaplen(int snap)
257 {
258 	if (priv_set_snaplen(snap))
259 		return (1);
260 
261 	if (cur_snaplen > snap)
262 		purge_buffer();
263 
264 	cur_snaplen = snap;
265 
266 	return (0);
267 }
268 
269 int
270 reset_dump(int nomove)
271 {
272 	int ret;
273 
274 	for (;;) {
275 		ret = try_reset_dump(nomove);
276 		if (ret <= 0)
277 			break;
278 	}
279 
280 	return (ret);
281 }
282 
283 /*
284  * tries to (re)open log file, nomove flag is used with -x switch
285  * returns 0: success, 1: retry (log moved), -1: error
286  */
287 int
288 try_reset_dump(int nomove)
289 {
290 	struct pcap_file_header hdr;
291 	struct stat st;
292 	int fd;
293 	FILE *fp;
294 
295 	if (hpcap == NULL)
296 		return (-1);
297 
298 	if (dpcap) {
299 		flush_buffer(dpcap);
300 		fclose(dpcap);
301 		dpcap = NULL;
302 	}
303 
304 	/*
305 	 * Basically reimplement pcap_dump_open() because it truncates
306 	 * files and duplicates headers and such.
307 	 */
308 	fd = priv_open_log();
309 	if (fd < 0)
310 		return (-1);
311 
312 	fp = fdopen(fd, "a+");
313 
314 	if (fp == NULL) {
315 		logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
316 		close(fd);
317 		return (-1);
318 	}
319 	if (fstat(fileno(fp), &st) == -1) {
320 		logmsg(LOG_ERR, "Error: %s: %s", filename, strerror(errno));
321 		fclose(fp);
322 		return (-1);
323 	}
324 
325 	/* set FILE unbuffered, we do our own buffering */
326 	if (setvbuf(fp, NULL, _IONBF, 0)) {
327 		logmsg(LOG_ERR, "Failed to set output buffers");
328 		fclose(fp);
329 		return (-1);
330 	}
331 
332 #define TCPDUMP_MAGIC 0xa1b2c3d4
333 
334 	if (st.st_size == 0) {
335 		if (snaplen != cur_snaplen) {
336 			logmsg(LOG_NOTICE, "Using snaplen %d", snaplen);
337 			if (set_snaplen(snaplen))
338 				logmsg(LOG_WARNING,
339 				    "Failed, using old settings");
340 		}
341 		hdr.magic = TCPDUMP_MAGIC;
342 		hdr.version_major = PCAP_VERSION_MAJOR;
343 		hdr.version_minor = PCAP_VERSION_MINOR;
344 		hdr.thiszone = hpcap->tzoff;
345 		hdr.snaplen = hpcap->snapshot;
346 		hdr.sigfigs = 0;
347 		hdr.linktype = hpcap->linktype;
348 
349 		if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
350 			fclose(fp);
351 			return (-1);
352 		}
353 	} else if (scan_dump(fp, st.st_size)) {
354 		fclose(fp);
355 		if (nomove || priv_move_log()) {
356 			logmsg(LOG_ERR,
357 			    "Invalid/incompatible log file, move it away");
358 			return (-1);
359 		}
360 		return (1);
361 	}
362 
363 	dpcap = fp;
364 
365 	set_suspended(0);
366 	flush_buffer(fp);
367 
368 	return (0);
369 }
370 
371 int
372 scan_dump(FILE *fp, off_t size)
373 {
374 	struct pcap_file_header hdr;
375 	struct pcap_pkthdr ph;
376 	off_t pos;
377 
378 	/*
379 	 * Must read the file, compare the header against our new
380 	 * options (in particular, snaplen) and adjust our options so
381 	 * that we generate a correct file. Furthermore, check the file
382 	 * for consistency so that we can append safely.
383 	 *
384 	 * XXX this may take a long time for large logs.
385 	 */
386 	fseek(fp, 0L, SEEK_SET);
387 
388 	if (fread((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
389 		logmsg(LOG_ERR, "Short file header");
390 		return (1);
391 	}
392 
393 	if (hdr.magic != TCPDUMP_MAGIC ||
394 	    hdr.version_major != PCAP_VERSION_MAJOR ||
395 	    hdr.version_minor != PCAP_VERSION_MINOR ||
396 	    (int)hdr.linktype != hpcap->linktype ||
397 	    hdr.snaplen > PFLOGD_MAXSNAPLEN) {
398 		return (1);
399 	}
400 
401 	pos = sizeof(hdr);
402 
403 	while (!feof(fp)) {
404 		off_t len = fread((char *)&ph, 1, sizeof(ph), fp);
405 		if (len == 0)
406 			break;
407 
408 		if (len != sizeof(ph))
409 			goto error;
410 		if (ph.caplen > hdr.snaplen || ph.caplen > PFLOGD_MAXSNAPLEN)
411 			goto error;
412 		pos += sizeof(ph) + ph.caplen;
413 		if (pos > size)
414 			goto error;
415 		fseek(fp, ph.caplen, SEEK_CUR);
416 	}
417 
418 	if (pos != size)
419 		goto error;
420 
421 	if ((int)hdr.snaplen != cur_snaplen) {
422 		logmsg(LOG_WARNING,
423 		       "Existing file has different snaplen %u, using it",
424 		       hdr.snaplen);
425 		if (set_snaplen(hdr.snaplen)) {
426 			logmsg(LOG_WARNING,
427 			       "Failed, using old settings, offset %llu",
428 			       (unsigned long long) size);
429 		}
430 	}
431 
432 	return (0);
433 
434  error:
435 	logmsg(LOG_ERR, "Corrupted log file.");
436 	return (1);
437 }
438 
439 /* dump a packet directly to the stream, which is unbuffered */
440 void
441 dump_packet_nobuf(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
442 {
443 	FILE *f = (FILE *)user;
444 
445 	if (suspended) {
446 		packets_dropped++;
447 		return;
448 	}
449 
450 	if (fwrite(h, sizeof(*h), 1, f) != 1) {
451 		off_t pos = ftello(f);
452 
453 		/* try to undo header to prevent corruption */
454 		if ((size_t)pos < sizeof(*h) ||
455 		    ftruncate(fileno(f), pos - sizeof(*h))) {
456 			logmsg(LOG_ERR, "Write failed, corrupted logfile!");
457 			set_suspended(1);
458 			gotsig_close = 1;
459 			return;
460 		}
461 		goto error;
462 	}
463 
464 	if (fwrite(sp, h->caplen, 1, f) != 1)
465 		goto error;
466 
467 	return;
468 
469 error:
470 	set_suspended(1);
471 	packets_dropped ++;
472 	logmsg(LOG_ERR, "Logging suspended: fwrite: %s", strerror(errno));
473 }
474 
475 int
476 flush_buffer(FILE *f)
477 {
478 	off_t offset;
479 	int len = bufpos - buffer;
480 
481 	if (len <= 0)
482 		return (0);
483 
484 	offset = ftello(f);
485 	if (offset == (off_t)-1) {
486 		set_suspended(1);
487 		logmsg(LOG_ERR, "Logging suspended: ftello: %s",
488 		    strerror(errno));
489 		return (1);
490 	}
491 
492 	if (fwrite(buffer, len, 1, f) != 1) {
493 		set_suspended(1);
494 		logmsg(LOG_ERR, "Logging suspended: fwrite: %s",
495 		    strerror(errno));
496 		ftruncate(fileno(f), offset);
497 		return (1);
498 	}
499 
500 	set_suspended(0);
501 	bufpos = buffer;
502 	bufleft = buflen;
503 	bufpkt = 0;
504 
505 	return (0);
506 }
507 
508 void
509 purge_buffer(void)
510 {
511 	packets_dropped += bufpkt;
512 
513 	set_suspended(0);
514 	bufpos = buffer;
515 	bufleft = buflen;
516 	bufpkt = 0;
517 }
518 
519 /* append packet to the buffer, flushing if necessary */
520 void
521 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
522 {
523 	FILE *f = (FILE *)user;
524 	size_t len = sizeof(*h) + h->caplen;
525 
526 	if (len < sizeof(*h) || h->caplen > (size_t)cur_snaplen) {
527 		logmsg(LOG_NOTICE, "invalid size %zd (%u/%u), packet dropped",
528 		       len, cur_snaplen, snaplen);
529 		packets_dropped++;
530 		return;
531 	}
532 
533 	if (len <= bufleft)
534 		goto append;
535 
536 	if (suspended) {
537 		packets_dropped++;
538 		return;
539 	}
540 
541 	if (flush_buffer(f)) {
542 		packets_dropped++;
543 		return;
544 	}
545 
546 	if (len > bufleft) {
547 		dump_packet_nobuf(user, h, sp);
548 		return;
549 	}
550 
551  append:
552 	memcpy(bufpos, h, sizeof(*h));
553 	memcpy(bufpos + sizeof(*h), sp, h->caplen);
554 
555 	bufpos += len;
556 	bufleft -= len;
557 	bufpkt++;
558 
559 	return;
560 }
561 
562 int
563 main(int argc, char **argv)
564 {
565 	struct pcap_stat pstat;
566 	int ch, np, ret, Xflag = 0;
567 	pcap_handler phandler = dump_packet;
568 	const char *errstr = NULL;
569 	char *pidf = NULL;
570 
571 	ret = 0;
572 
573 	/* Neither FreeBSD nor DFly have this; Max seems to think this may
574 	 * be a paranoid check. Comment it out:
575 	closefrom(STDERR_FILENO + 1);
576 	 */
577 
578 	while ((ch = getopt(argc, argv, "Dxd:f:i:p:s:")) != -1) {
579 		switch (ch) {
580 		case 'D':
581 			Debug = 1;
582 			break;
583 		case 'd':
584 			delay = strtonum(optarg, 5, 60*60, &errstr);
585 			if (errstr)
586 				usage();
587 			break;
588 		case 'f':
589 			filename = optarg;
590 			break;
591 		case 'i':
592 			interface = optarg;
593 			break;
594 		case 'p':
595 			pidf = optarg;
596 			break;
597 		case 's':
598 			snaplen = strtonum(optarg, 0, PFLOGD_MAXSNAPLEN,
599 			    &errstr);
600 			if (snaplen <= 0)
601 				snaplen = DEF_SNAPLEN;
602 			if (errstr)
603 				snaplen = PFLOGD_MAXSNAPLEN;
604 			break;
605 		case 'x':
606 			Xflag++;
607 			break;
608 		default:
609 			usage();
610 		}
611 
612 	}
613 
614 	log_debug = Debug;
615 	argc -= optind;
616 	argv += optind;
617 
618 	/* does interface exist */
619 	if (!if_exists(__DECONST(char *, interface))) {
620 		warn("Failed to initialize: %s", interface);
621 		logmsg(LOG_ERR, "Failed to initialize: %s", interface);
622 		logmsg(LOG_ERR, "Exiting, init failure");
623 		exit(1);
624 	}
625 
626 	if (!Debug) {
627 		openlog("pflogd", LOG_PID | LOG_CONS, LOG_DAEMON);
628 		if (daemon(0, 0)) {
629 			logmsg(LOG_WARNING, "Failed to become daemon: %s",
630 			    strerror(errno));
631 		}
632 		pidfile(pidf);
633 	}
634 
635 	umask(S_IRWXG | S_IRWXO);
636 
637 	/* filter will be used by the privileged process */
638 	if (argc) {
639 		filter = copy_argv(argv);
640 		if (filter == NULL)
641 			logmsg(LOG_NOTICE, "Failed to form filter expression");
642 	}
643 
644 	/* initialize pcap before dropping privileges */
645 	if (init_pcap()) {
646 		logmsg(LOG_ERR, "Exiting, init failure");
647 		exit(1);
648 	}
649 
650 	/* Privilege separation begins here */
651 	if (priv_init()) {
652 		logmsg(LOG_ERR, "unable to privsep");
653 		exit(1);
654 	}
655 
656 	setproctitle("[initializing]");
657 	/* Process is now unprivileged and inside a chroot */
658 	signal(SIGTERM, sig_close);
659 	signal(SIGINT, sig_close);
660 	signal(SIGQUIT, sig_close);
661 	signal(SIGALRM, sig_alrm);
662 	signal(SIGHUP, sig_hup);
663 	alarm(delay);
664 
665 	buffer = malloc(PFLOGD_BUFSIZE);
666 
667 	if (buffer == NULL) {
668 		logmsg(LOG_WARNING, "Failed to allocate output buffer");
669 		phandler = dump_packet_nobuf;
670 	} else {
671 		bufleft = buflen = PFLOGD_BUFSIZE;
672 		bufpos = buffer;
673 		bufpkt = 0;
674 	}
675 
676 	if (reset_dump(Xflag) < 0) {
677 		if (Xflag)
678 			return (1);
679 
680 		logmsg(LOG_ERR, "Logging suspended: open error");
681 		set_suspended(1);
682 	} else if (Xflag)
683 		return (0);
684 
685 	while (1) {
686 		np = pcap_dispatch(hpcap, PCAP_NUM_PKTS,
687 		    phandler, (u_char *)dpcap);
688 		if (np < 0) {
689 			if (!if_exists(__DECONST(char *, interface)) == -1) {
690 				logmsg(LOG_NOTICE, "interface %s went away",
691 				    interface);
692 				ret = -1;
693 				break;
694 			}
695 			logmsg(LOG_NOTICE, "%s", pcap_geterr(hpcap));
696 		}
697 
698 		if (gotsig_close)
699 			break;
700 		if (gotsig_hup) {
701 			if (reset_dump(0)) {
702 				logmsg(LOG_ERR,
703 				    "Logging suspended: open error");
704 				set_suspended(1);
705 			}
706 			gotsig_hup = 0;
707 		}
708 
709 		if (gotsig_alrm) {
710 			if (dpcap)
711 				flush_buffer(dpcap);
712 			else
713 				gotsig_hup = 1;
714 			gotsig_alrm = 0;
715 			alarm(delay);
716 		}
717 	}
718 
719 	logmsg(LOG_NOTICE, "Exiting");
720 	if (dpcap) {
721 		flush_buffer(dpcap);
722 		fclose(dpcap);
723 	}
724 	purge_buffer();
725 
726 	if (pcap_stats(hpcap, &pstat) < 0)
727 		logmsg(LOG_WARNING, "Reading stats: %s", pcap_geterr(hpcap));
728 	else
729 		logmsg(LOG_NOTICE,
730 		    "%u packets received, %u/%ld dropped (kernel/pflogd)",
731 		    pstat.ps_recv, pstat.ps_drop, packets_dropped);
732 
733 	pcap_close(hpcap);
734 	if (!Debug)
735 		closelog();
736 	return (ret);
737 }
738