summaryrefslogtreecommitdiff
path: root/sbin/pflogd/pflogd.c
blob: eecaf97afaca4a4c22e7c6fb599f589b9e6c8615 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*	$OpenBSD: pflogd.c,v 1.20 2003/05/14 08:56:12 canacar Exp $	*/

/*
 * Copyright (c) 2001 Theo de Raadt
 * Copyright (c) 2001 Can Erkin Acar
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *    - Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *    - Redistributions in binary form must reproduce the above
 *      copyright notice, this list of conditions and the following
 *      disclaimer in the documentation and/or other materials provided
 *      with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pcap-int.h>
#include <pcap.h>
#include <syslog.h>
#include <signal.h>
#include <errno.h>
#include <stdarg.h>
#include <fcntl.h>
#include <util.h>

#define DEF_SNAPLEN 116		/* default plus allow for larger header of pflog */
#define PCAP_TO_MS 500		/* pcap read timeout (ms) */
#define PCAP_NUM_PKTS 1000	/* max number of packets to process at each loop */
#define PCAP_OPT_FIL 0		/* filter optimization */
#define FLUSH_DELAY 60		/* flush delay */

#define PFLOGD_LOG_FILE		"/var/log/pflog"
#define PFLOGD_DEFAULT_IF	"pflog0"

pcap_t *hpcap;
pcap_dumper_t *dpcap;

int Debug = 0;
int snaplen = DEF_SNAPLEN;

volatile sig_atomic_t gotsig_close, gotsig_alrm, gotsig_hup;

char *filename = PFLOGD_LOG_FILE;
char *interface = PFLOGD_DEFAULT_IF;
char *filter = NULL;

char errbuf[PCAP_ERRBUF_SIZE];

int log_debug = 0;
unsigned int delay = FLUSH_DELAY;

char *copy_argv(char * const *argv);
int   init_pcap(void);
void  logmsg(int priority, const char *message, ...);
int   reset_dump(void);
void  sig_alrm(int);
void  sig_close(int);
void  sig_hup(int);
void  usage(void);


char *
copy_argv(char * const *argv)
{
	size_t len = 0, n;
	char *buf;

	if (argv == NULL)
		return (NULL);

	for (n = 0; argv[n]; n++)
		len += strlen(argv[n])+1;
	if (len == 0)
		return (NULL);

	buf = malloc(len);
	if (buf == NULL)
		return (NULL);

	strlcpy(buf, argv[0], len);
	for (n = 1; argv[n]; n++) {
		strlcat(buf, " ", len);
		strlcat(buf, argv[n], len);
	}
	return (buf);
}

void
logmsg(int pri, const char *message, ...)
{
	va_list ap;
	va_start(ap, message);

	if (log_debug) {
		vfprintf(stderr, message, ap);
		fprintf(stderr, "\n");
	} else
		vsyslog(pri, message, ap);
	va_end(ap);
}

__dead void
usage(void)
{
	fprintf(stderr, "usage: pflogd [-D] [-d delay] [-f filename] ");
	fprintf(stderr, "[-s snaplen] [expression]\n");
	exit(1);
}

void
sig_close(int sig)
{
	gotsig_close = 1;
}

void
sig_hup(int sig)
{
	gotsig_hup = 1;
}

void
sig_alrm(int sig)
{
	gotsig_alrm = 1;
}

int
init_pcap(void)
{
	struct bpf_program bprog;
	pcap_t *oldhpcap = hpcap;

	hpcap = pcap_open_live(interface, snaplen, 1, PCAP_TO_MS, errbuf);
	if (hpcap == NULL) {
		logmsg(LOG_ERR, "Failed to initialize: %s", errbuf);
		hpcap = oldhpcap;
		return (-1);
	}

	if (pcap_compile(hpcap, &bprog, filter, PCAP_OPT_FIL, 0) < 0)
		logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
	else if (pcap_setfilter(hpcap, &bprog) < 0)
		logmsg(LOG_WARNING, "%s", pcap_geterr(hpcap));
	if (filter != NULL)
		free(filter);

	if (pcap_datalink(hpcap) != DLT_PFLOG) {
		logmsg(LOG_ERR, "Invalid datalink type");
		pcap_close(hpcap);
		hpcap = oldhpcap;
		return (-1);
	}

	if (oldhpcap)
		pcap_close(oldhpcap);

	snaplen = pcap_snapshot(hpcap);
	return (0);
}

int
reset_dump(void)
{
	struct pcap_file_header hdr;
	struct stat st;
	int tmpsnap;
	FILE *fp;

	if (hpcap == NULL)
		return (1);
	if (dpcap) {
		pcap_dump_close(dpcap);
		dpcap = 0;
	}

	/*
	 * Basically reimpliment pcap_dump_open() because it truncates
	 * files and duplicates headers and such.
	 */
	fp = fopen(filename, "a+");
	if (fp == NULL) {
		snprintf(hpcap->errbuf, PCAP_ERRBUF_SIZE, "%s: %s",
		    filename, pcap_strerror(errno));
		logmsg(LOG_ERR, "Error: %s", pcap_geterr(hpcap));
		return (1);
	}
	if (fstat(fileno(fp), &st) == -1) {
		snprintf(hpcap->errbuf, PCAP_ERRBUF_SIZE, "%s: %s",
		    filename, pcap_strerror(errno));
		logmsg(LOG_ERR, "Error: %s", pcap_geterr(hpcap));
		return (1);
	}

	dpcap = (pcap_dumper_t *)fp;

#define TCPDUMP_MAGIC 0xa1b2c3d4

	if (st.st_size == 0) {
		if (snaplen != pcap_snapshot(hpcap)) {
			logmsg(LOG_NOTICE, "Using snaplen %d", snaplen);
			if (init_pcap()) {
				logmsg(LOG_ERR, "Failed to initialize");
				if (hpcap == NULL) return (-1);
				logmsg(LOG_NOTICE, "Using old settings");
			}
		}
		hdr.magic = TCPDUMP_MAGIC;
		hdr.version_major = PCAP_VERSION_MAJOR;
		hdr.version_minor = PCAP_VERSION_MINOR;
		hdr.thiszone = hpcap->tzoff;
		hdr.snaplen = hpcap->snapshot;
		hdr.sigfigs = 0;
		hdr.linktype = hpcap->linktype;

		if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1) {
			dpcap = NULL;
			fclose(fp);
			return (-1);
		}
		return (0);
	}

	/*
	 * XXX Must read the file, compare the header against our new
	 * options (in particular, snaplen) and adjust our options so
	 * that we generate a correct file.
	 */
	(void) fseek(fp, 0L, SEEK_SET);
	if (fread((char *)&hdr, sizeof(hdr), 1, fp) == 1) {
		if (hdr.magic != TCPDUMP_MAGIC ||
		    hdr.version_major != PCAP_VERSION_MAJOR ||
		    hdr.version_minor != PCAP_VERSION_MINOR ||
		    hdr.linktype != hpcap->linktype) {
			logmsg(LOG_ERR,
			    "Invalid/incompatible log file, move it away");
			fclose(fp);
			return (1);
		    }
		if (hdr.snaplen != snaplen) {
			logmsg(LOG_WARNING,
			    "Existing file specifies a snaplen of %u, using it",
			    hdr.snaplen);
			tmpsnap = snaplen;
			snaplen = hdr.snaplen;
			if (init_pcap()) {
				logmsg(LOG_ERR, "Failed to re-initialize");
				if (hpcap == 0)
					return (-1);
				logmsg(LOG_NOTICE,
					"Using old settings, offset: %llu",
					(unsigned long long)st.st_size);
			}
			snaplen = tmpsnap;
		}
	}

	(void) fseek(fp, 0L, SEEK_END);
	return (0);
}

int
main(int argc, char **argv)
{
	struct pcap_stat pstat;
	int ch, np;

	while ((ch = getopt(argc, argv, "Dd:s:f:")) != -1) {
		switch (ch) {
		case 'D':
			Debug = 1;
			break;
		case 'd':
			delay = atoi(optarg);
			if (delay < 5 || delay > 60*60)
				usage();
			break;
		case 'f':
			filename = optarg;
			break;
		case 's':
			snaplen = atoi(optarg);
			if (snaplen <= 0)
				snaplen = DEF_SNAPLEN;
			break;
		default:
			usage();
		}

	}

	log_debug = Debug;
	argc -= optind;
	argv += optind;

	if (!Debug) {
		openlog("pflogd", LOG_PID | LOG_CONS, LOG_DAEMON);
		if (daemon(0, 0)) {
			logmsg(LOG_WARNING, "Failed to become daemon: %s",
			    strerror(errno));
		}
		pidfile(NULL);
	}

	(void)umask(S_IRWXG | S_IRWXO);

	signal(SIGTERM, sig_close);
	signal(SIGINT, sig_close);
	signal(SIGQUIT, sig_close);
	signal(SIGALRM, sig_alrm);
	signal(SIGHUP, sig_hup);
	alarm(delay);

	if (argc) {
		filter = copy_argv(argv);
		if (filter == NULL)
			logmsg(LOG_NOTICE, "Failed to form filter expression");
	}

	if (init_pcap()) {
		logmsg(LOG_ERR, "Exiting, init failure");
		exit(1);
	}

	if (reset_dump()) {
		logmsg(LOG_ERR, "Failed to open log file %s", filename);
		pcap_close(hpcap);
		exit(1);
	}

	while (1) {
		np = pcap_dispatch(hpcap, PCAP_NUM_PKTS, pcap_dump, (u_char *)dpcap);
		if (np < 0)
			logmsg(LOG_NOTICE, "%s", pcap_geterr(hpcap));

		if (gotsig_close)
			break;
		if (gotsig_hup) {
			if (reset_dump()) {
				logmsg(LOG_ERR, "Failed to open log file!");
				break;
			}
			logmsg(LOG_NOTICE, "Reopened logfile");
			gotsig_hup = 0;
		}

		if (gotsig_alrm) {
			/* XXX pcap_dumper is an incomplete type which libpcap
			 * casts to a FILE* currently.  For now it is safe to
			 * make the same assumption, however this may change
			 * in the future.
			 */
			if (dpcap) {
				if (fflush((FILE *)dpcap) == EOF) {
					break;
				}
			}
			gotsig_alrm = 0;
			alarm(delay);
		}
	}

	logmsg(LOG_NOTICE, "Exiting due to signal");
	if (dpcap)
		pcap_dump_close(dpcap);

	if (pcap_stats(hpcap, &pstat) < 0)
		logmsg(LOG_WARNING, "Reading stats: %s", pcap_geterr(hpcap));
	else
		logmsg(LOG_NOTICE, "%u packets received, %u dropped",
		    pstat.ps_recv, pstat.ps_drop);

	pcap_close(hpcap);
	if (!Debug)
		closelog();
	return (0);
}