aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 3760296d0fc48e6c4b76ef49960e87acd6608386 (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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/* This file is part of IPACCT
   Copyright (C) 1999,2000,2001,2002,2003,2004,2005,2008 Sergey Poznyakoff 

   Ipacct is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   Ipacct is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Ipacct.  If not, see <http://www.gnu.org/licenses/>. */

#if defined(HAVE_CONFIG_H)
# include <config.h>
#endif

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <syslog.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <getopt.h>
#include <pcap.h>
#include <argp.h>
#include <ipacct.h>

#ifndef RETSIGTYPE
# define RETSIGTYPE void
#endif

RETSIGTYPE sig_hup();
RETSIGTYPE sig_usr1();
RETSIGTYPE sig_usr2();
RETSIGTYPE sig_child();
static pcap_t  * init(char *device, char *cmd);

int dump_bytecode;        /* dump the packet-matched code and exit */
int promisc_off;          /* do not put the interface into promiscuous mode */
int optimize_expr;        /* optimize compiled expression */
int foreground;           /* remain in the foreground */
int fixed_clocks;         /* use fixed clocks */
int single_process = 0;   /* don't fork separate processes for accounting */
int verbose = 0;
char *profile = SYSCONFDIR "/" PROFILE;
char dump_name[MAX_PATH_LENGTH];
char *log_name;

char *device;
int snaplen = 96;
unsigned int localnet = 0, netmask = 0;
time_t start_time;
time_t slice_interval = TIME_TO_WAIT;
static pcap_t *pcap;
static char pidfile[MAX_PATH_LENGTH];

static char *infile = NULL;
static char *expr = NULL;
static time_t ttw = 0;
static int syntax_check = 0;    /* check the config file and exit */
static int test_mode = 0;
char *user = NULL;

const char *argp_program_version = "ipacct (" PACKAGE ") " VERSION;
static char doc[] = "ip traffic accounting daemon";

static struct argp_option options[] = {
	{ "dump-bytecode", 'b', 0, 0,
	  "Dump compiled packet comparison bytecode to stdout and exit", 0},
	{ "config", 'c', "FILE", 0,
	  "Specify alternative configuration file", 0 },
	{ "foreground", 'f', NULL, 0,
	  "Run in foreground", 0 },
	{ "file", 'F', "FILE", OPTION_HIDDEN,
	  "", 0 },
	{ "interface", 'i', "DEVICE", 0,
	  "Specify interface to listen on", 0 },
	{ "log-file", 'l', "FILE", 0,
	  "Set log file name", 0 },
	{ "optimize", 'O', NULL, 0,
	  "Optimize bytecode", 0 },
	{ "no-promiscuous-mode", 'p', NULL, 0,
	  "Do not put the inteface into promiscuous mode", 0 },
	{ "single-process", 's', NULL, 0,
	  "Run in single-process mode", 0 },
	{ "syntax-check", 'S', NULL, 0,
	  "Check config file for errors and exit", 0 },
	{ "timeslice", 't', "NUMBER", 0,
	  "Set timeslice value in seconds", 0 },
	{ "test-shell", 'T', NULL, 0,
	  "Start test shell", 0 },
	{ "verbose", 'v', NULL, 0,
	  "Increase verbosity level", 0 },
	{ "fixed-clocks", 'x', NULL, 0,
	  "Dump statistics at precise time intervals", 0 },
	{ "user", 'u', "USER-NAME", 0,
	  "Run with this user privileges", 0 },
	{NULL, 0, NULL, 0, NULL, 0}
};


/*ARGSUSED*/
static error_t
parse_opt(int key, char *arg, struct argp_state *state)
{
	switch (key) {
	case 'b':
		dump_bytecode++;
		break;
	case 'c':
		profile = arg;
		break;
	case 'f':
		foreground++;
		break;
	case 'F':
		infile = arg;
		break;
	case 'i':
		device = arg;
		break;
	case 'l':
		log_name = arg;
		break;
	case 'O':
		optimize_expr++;
		break;
	case 'p':
		promisc_off++;
		break;
	case 's':
		single_process++;
		break;
	case 'S':
		syntax_check++;
		break;
	case 't':
		ttw = atoi(arg);
		if (ttw <= 0) 
			die(1, "invalid timeslice value (%d)", ttw);
		break;
	case 'T':
		test_mode++;
		foreground++;
		break;
	case 'v':
		verbose++;
		if (verbose > 2)
			debug_profile();
		break;
	case 'x':
		fixed_clocks++;
		break;
	case 'u':
		user = arg;
		break;
	default:
		return ARGP_ERR_UNKNOWN;
	}
	return 0;
}

static struct argp argp = {
	options,
	parse_opt,
	NULL,
	doc,
	NULL,
	NULL, NULL
};

/* Change to the given uid/gid. Clear the supplementary group list.
   On success returns 0.
   On failure returns 1 (or exits, depending on topt settings. See
   anubis_error) */
static int
change_privs (uid_t uid, gid_t gid)
{
	int rc = 0;
	gid_t emptygidset[1];

	/* Reset group permissions */
	emptygidset[0] = gid ? gid : getegid();
	if (geteuid() == 0 && setgroups(1, emptygidset)) {
		error ("setgroups(1, %lu) failed: %s",
			(u_long) emptygidset[0],
		       strerror (errno));
		rc = 1;
	}

	/* Switch to the user's gid. On some OSes the effective gid must
	   be reset first */

#if defined(HAVE_SETEGID)
	if ((rc = setegid(gid)) < 0)
		error ("setegid(%lu) failed: %s",
		       (u_long) gid, strerror (errno));
#elif defined(HAVE_SETREGID)
	if ((rc = setregid(gid, gid)) < 0)
		error ("setregid(%lu,%lu) failed: %s",
			(u_long) gid, (u_long) gid, strerror (errno));
#elif defined(HAVE_SETRESGID)
	if ((rc = setresgid(gid, gid, gid)) < 0)
		error ("setresgid(%lu,%lu,%lu) failed: %s",
		       (u_long) gid,
		       (u_long) gid,
		       (u_long) gid,
		       strerror (errno));
#endif

	if (rc == 0 && gid != 0) {
		if ((rc = setgid(gid)) < 0 && getegid() != gid) 
			error ("setgid(%lu) failed: %s",
			       (u_long) gid,
			       strerror (errno));
		if (rc == 0 && getegid() != gid) {
			error("cannot set effective gid to %lu: %s",
			      (u_long) gid,
			      strerror (errno));
			rc = 1;
		}
	}

	/* now reset uid */
	if (rc == 0 && uid != 0) {
		uid_t euid;

		if (setuid(uid)
		    || geteuid() != uid
		    || (getuid() != uid
			&& (geteuid() == 0 || getuid() == 0))) {
			
#if defined(HAVE_SETREUID)
			if (geteuid() != uid) {
				if (setreuid(uid, -1) < 0) {
					error ("setreuid(%lu,-1) failed: %s",
					       (u_long) uid,
					       strerror (errno));
					rc = 1;
				}
				if (setuid(uid) < 0) {
					error ("second setuid(%lu) failed: %s",
					       (u_long) uid,
					       strerror (errno));
					rc = 1;
				}
			} else
#endif
				{
					error ("setuid(%lu) failed: %s",
					       (u_long) uid,
					       strerror (errno));
					rc = 1;
				}
		}
	

		euid = geteuid();
		if (uid != 0 && setuid(0) == 0) {
			error ("seteuid(0) succeeded when it should not");
			rc = 1;
		} else if (uid != euid && setuid(euid) == 0) {
			error ("cannot drop non-root setuid privileges");
			rc = 1;
		}
	}
	return rc;
}

void
change_user ()
{
	struct passwd *pwd;
	
	if (user == NULL)
		return;
	
	pwd = getpwnam (user);
	if (pwd) {
		if (change_privs (pwd->pw_uid, pwd->pw_gid))
			exit (1);
	
		chdir (pwd->pw_dir);
		syslog (LOG_INFO, "UID:%d (%s), GID:%d, EUID:%d, EGID:%d",
			(int) getuid (), pwd->pw_name, (int) getgid (),
			(int) geteuid (), (int) getegid ());
	}
}

int
main(int argc, char **argv)
{
	int c, type;
	pcap_handler callback;
	pid_t pid;
	int index;
	
	if (argp_parse(&argp, argc, argv, 0, &index, NULL))
		exit(1);

	read_profile(profile);
	if (syntax_check)
		return 0;
	if (test_mode)
		return test_shell();
	
	alloc_snap_buffer();

	if (infile) {
		if (index < argc) 
			die(1, "excess arguments after %s", argv[index]);
		expr = read_expr(infile);
	} else if (index < argc) 
		expr = copy_argv(argc, argv, index);

	
	pcap = init(device, expr);
	if (!(callback = lookup_pcap_callback(type = pcap_datalink(pcap))))
		die(1, "unknown data link type 0x%x", type);

	start_time = time(NULL);
	if (ttw)
		slice_interval = ttw;
	
	if (!foreground) {
		int i;
		pid_t pid = fork();
		if (pid < 0) 
			die(1, "cannot fork: %s", strerror(errno));
		if (pid > 0) {
			/* Parent branch */
			FILE *fp;
			/* write pid file */
			if ((fp = fopen(pidfile, "w")) != NULL) {
				fprintf(fp, "%d\n", pid);
				fclose(fp);
			} else {
				error("can't write pid file %s: %s",
				      pidfile, strerror(errno));
			}
			exit(0);
		}
		/* Child branch */
		chdir("/");
		for (i = 0; i < 3; i++)
			close(i);
		setsid();
		init_syslog();
	}

	change_user();
	run(pcap, callback);

	cleanup();
	return 0;
}

pcap_t  *
init(char *device, char *cmdbuf)
{
	char buf[PCAP_ERRBUF_SIZE];
	struct bpf_program bpfcode;
	pcap_t *pd;
	pid_t pid;
	
	if (!device)
		if (!(device = pcap_lookupdev(buf)))
			die(1, buf);

	sprintf(pidfile, "/var/run/ipacct-%s.pid", device);
	if (!foreground && (pid = get_pid_from_file(pidfile)) > 0) 
		die(1, "the ipacct daemon seems to be running under pid %d.\n"
		    "If it is not, remove `%s' file and start ipacct again",
		    pid, pidfile);
	
	
	if (pd = pcap_open_live(device, snaplen, !promisc_off, 1000, buf)) {
		if ((pcap_lookupnet(device,
				    (u_int *) &localnet, (u_int *) & netmask,
				    buf)) < 0)
			die(1, buf);
	} else
		die(1, buf);
	
	setuid(getuid());

	memset(&bpfcode, 0, sizeof(bpfcode));

	if (pcap_compile(pd, &bpfcode, cmdbuf, optimize_expr, netmask) < 0)
		die(1, pcap_geterr(pd));

	if (dump_bytecode) {
		bpf_dump(&bpfcode, dump_bytecode);
		exit(0);
	}
	if (pcap_setfilter(pd, &bpfcode) < 0)
		die(1, pcap_geterr(pd));

	signal(SIGPIPE, SIG_IGN);
	signal(SIGHUP, sig_hup);
        signal(SIGINT, (RETSIGTYPE (*)())cleanup);
	signal(SIGTERM, (RETSIGTYPE (*)())cleanup);
	signal(SIGUSR1, sig_usr1);
	signal(SIGUSR2, sig_usr2);
	signal(SIGCHLD, sig_child);

/*	cons_init();*/
	return pd;
}


int
open_process()
{
	pid_t pid;

	if (single_process)
		return 0;

	pid = fork();
	if (pid > 0) 
		return 1;
	else if (pid < 0) {
		error("fork: %s", strerror(errno));
		return -1;
	}
	
	signal(SIGHUP, SIG_IGN);
	signal(SIGUSR1, SIG_IGN);
	signal(SIGUSR2, SIG_IGN);
	signal(SIGCHLD, SIG_IGN);
	return 0;
}

int
close_process()
{
	if (!single_process)
		exit(0);
}

void
re_read_profile(char *name)
{
	account_init();
	read_profile(name);
}

void
cleanup()
{
	pcap_close(pcap);
	if (!foreground)
		unlink(pidfile);
	exit(0);
}

RETSIGTYPE
sig_hup()
{
	syslog(LOG_INFO, "reconfiguring");
	re_read_profile(profile);
	signal(SIGHUP, sig_hup);
}

RETSIGTYPE
sig_usr1(sig)
	int sig;
{
	dump_table(time(NULL));
	signal(SIGUSR1, sig_usr1);
}

RETSIGTYPE
sig_usr2()
{
}

RETSIGTYPE
sig_child(int sig)
{
	int status;
	while (waitpid((pid_t)-1, &status, WNOHANG) > 0)
		;
	signal(sig, sig_child);
}

Return to:

Send suggestions and report system problems to the System administrator.